<template>
  <div class="ContainerBox">
    <section class="ContainerBoxList">
      <!-- 按钮区域 -->
      <section class="buttonBox">
        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="8"></el-col>
          <el-col :span="16">
            <div class="rightBox">
              <el-cascader
                style="width: 100%; margin: 0 20px"
                placeholder="请选择监管地区"
                v-model="params.superviseDepartIdArr"
                v-if="
                  params.industryCode !== '03' &&
                  params.industryCode !== '04' &&
                  params.industryCode !== '05' &&
                  params.industryCode !== '07'
                "
                :options="areaCityListArr"
                @change="placeOfSuperviseCodeChange"
              >
              </el-cascader>

              <el-input
                v-model="params.name"
                placeholder="输入公司名称"
                clearable
                style="width: 600px"
              />
              <el-select
                v-model="params.statuses"
                collapse-tags
                multiple
                clearable
                style="width: 600px; margin: 0 20px"
                placeholder="请选择审批状态"
              >
                <el-option
                  v-for="item in statusesoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button type="primary" @click="exportExcel">导出</el-button>
            </div>
          </el-col>
        </el-row>
      </section>
      <!-- 内容区域 -->
      <section class="contentBox">
        <el-table
          :data="tableDataApprove"
          ref="districtTable"
          max-height="750"
          default-expand-all
          row-key="id"
          @selection-change="handleSelectionChange"
          @select-all="handleSelectionAllChange"
        >
          <el-table-column
            v-for="(item, index) in tableColumn"
            :key="index"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            v-if="item.show"
          >
            <template slot-scope="scope">
              <span v-if="item.prop == 'index'">
                {{
                  scope.$index + 1 + params.pageSize * (params.pageIndex - 1)
                }}
              </span>
              <span v-else>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
            <template slot-scope="scope">
              <el-button
                @click="ApprovedOrgBtn(scope.row)"
                type="text"
                size="small"
                class="primaryColor"
                v-if="scope.row.status === '待审批'"
                >审批</el-button
              >
              <el-button
                @click="ApprovedOrgDetail(scope.row)"
                type="text"
                size="small"
                class="primaryColor"
                >详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页页签 -->
        <pages
          :total="params.total"
          :currentPage.sync="params.pageIndex"
          :pageSize="params.pageSize"
          @handleCurrentChangeSub="handleCurrentChange"
          @handleSizeChangeSub="handleSizeChange"
        ></pages>
      </section>

      <el-drawer
        title="详情"
        :visible.sync="drawer"
        :direction="direction"
        :size="size"
      >
        <ApproveDetail
          v-if="drawer"
          :organizationId="organizationId"
          :formList="formList"
          :status="status"
          :industryCode="params.industryCode"
        ></ApproveDetail>
      </el-drawer>
    </section>
    <ApproveModal ref="approveRef" @refresh="approveOrgTableList" />
  </div>
</template>
<script>
import {
  cityOptionsListApi,
  dictRegisterListApi,
  approveOrgTableListApi,
  ApprovedOrgBtnApi,
  ApprovedOrgDetailApi,
  StaffDepartmentListApi,
  highSearchEmplyeeApi,
  exportOrgExcelApproveOrgApi,
} from "@/api/staffApi.js";

import selectTree from "@/components/SelectTree";
import { CodeToText } from "element-china-area-data"; //省市区联动插件
import ApproveDetail from "./ApproveDetail.vue";
import ApproveModal from "./ApproveModal.vue";

export default {
  data() {
    return {
      detailList: {},
      companyName: "",
      size: "600px",
      drawer: false,
      direction: "rtl",
      tableData: [],
      tableDataApprove: [],
      multipleSelection: [], //全选列表
      tableColumn: [
        { prop: "index", label: "序号", width: "100", show: true },
        { prop: "name", label: "公司名称", width: "250", show: true },
        { prop: "industryName", label: "行业类型", width: "100", show: true },
        {
          prop: "institutionalName",
          label: "机构类型",
          width: "150",
          show: true,
        },
        {
          prop: "placeOfRegister",
          label: "注册地区",
          width: "180",
          show: true,
        },
        {
          prop: "placeOfBusiness",
          label: "经营地区",
          width: "180",
          show: true,
        },
        {
          prop: "superviseRegionName",
          label: "监管地区",
          width: "180",
          show: true,
        },
        {
          prop: "superviseDepartName",
          label: "监管机构",
          width: "180",
          show: true,
        },
        { prop: "status", label: "审批状态", width: "180", show: true },
        { prop: "createdTime", label: "创建时间", width: "180", show: true },
        { prop: "approveTime", label: "审批时间", width: "180", show: true },
      ],
      params: {
        //搜索条件
        pageIndex: 1,
        pageSize: 10,
        industryCode: "",
        superviseDepartIdArr: null,
        name: "",
        statuses: "",
        total: 0,
        placeOfSupervise: {
          province: { code: "", name: "" },
          city: { code: "", name: "" },
          district: { code: "", name: "" },
        },
      },
      statusesoptions: [
        // { label: "全部", value: "" },
        { label: "待审批", value: "Init" },
        { label: "审批不通过", value: "NoPassed" },
        { label: "审批通过", value: "Passed" },
      ],
      areaCityListArr: [], //省市区列表
      organizationId: "",
      formList: {},
      status: "", //审批通过--查看详情，隐藏保存按钮
    };
  },
  components: {
    selectTree, //注册组件
    ApproveDetail,
    ApproveModal
  },
  async mounted() {
    let { industryCode } = this.$route.query;
    industryCode ? (this.params.industryCode = industryCode) : null;
    industryCode === "03" || industryCode === "04" || industryCode === "05"
      ? this.tableColumn.forEach((el) => {
          el.prop === "superviseRegionName" || el.prop === "superviseDepartName"
            ? (el.show = false)
            : null;
        })
      : null;
    industryCode === "06"
      ? this.tableColumn.forEach((el) => {
          el.prop === "placeOfRegister" || el.prop === "placeOfBusiness"
            ? (el.show = false)
            : null;
        })
      : null;
    industryCode === "07"
      ? this.tableColumn.forEach((el) => {
          el.prop === "superviseRegionName" ||
          el.prop === "placeOfRegister" ||
          el.prop === "superviseDepartName"
            ? (el.show = false)
            : null;
          el.prop === "placeOfBusiness" ? (el.label = "办公地区") : null;
        })
      : null;
    await this.areaCityList(); // 省市区层级
    await this.dictRegisterList(); // 所有字典表
    this.approveOrgTableList(); // 列表表格
  },
  watch: {
    multipleSelection() {
      if (this.multipleSelection.length) {
        this.disabled = false;
      } else {
        this.disabled = true;
      }
    },
  },
  methods: {
    areaCityList() {
      // console.log(55)
      return new Promise((resolve) => {
        cityOptionsListApi().then((response) => {
          console.log(response);
          console.log(5);
          // if (response.data) {
          this.areaCityListArr = response.data;
          console.log("22", this.areaCityListArr);
          // this.form.placeOfSuperviseCode = ['110000', '110100', '110101']//['100000', '101500', '101500']
          // }
          resolve(response);
        });
      });
    },
    dictRegisterList() {
      return new Promise((resolve) => {
        dictRegisterListApi().then((response) => {
          console.log(6);
          console.log(response);
          // if (response.data) {
          this.dictRegisterListObj = response.data;
          // }
          resolve(response);
        });
      });
    },
    placeOfSuperviseCodeChange(value) {
      console.log(value);
      console.log(
        "this.params.superviseDepartIdArr",
        this.params.superviseDepartIdArr
      );
      this.params.placeOfSupervise = {
        province: { code: value[0], name: CodeToText[value[0]] },
        city: { code: value[1], name: CodeToText[value[1]] },
        district: { code: value[2], name: CodeToText[value[2]] },
      };
    },
    exportExcel() {
      //导出
      let obj2 = { domainId: this.$route.query.domainId };
      exportOrgExcelApproveOrgApi(this.params, obj2).then((response) => {
        console.log(response);
        const content = response;
        const blob = new Blob([content]);
        const fileName = `组织信息.xlsx`;
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      });
    },
    addUser() {
      //添加员工弹窗
      this.showdialog = true;
    },
    switchHigh() {
      //切换高级搜索
      this.HighSearchFlag = !this.HighSearchFlag;
    },
    search() {
      //查询
      this.params.pageIndex = 1; //重置第一页
      //   let obj2={domainId:this.$route.query.domainId}
      approveOrgTableListApi(this.params).then((response) => {
        console.log("response", response);
        if (response.data.data) {
          this.tableDataApprove = response.data.data;
          this.params.total = response.data.total;
        }
      });
    },
    highSearch() {
      //高级查询
      this.params.pageIndex = 1; //重置第一页
      let obj2 = { domainId: this.$route.query.domainId };
      highSearchEmplyeeApi(this.params, obj2).then((response) => {
        if (response.data.data) {
          this.tableDataApprove = response.data.data;
          this.params.total = response.data.total;
        }
      });
    },
    resetSearchForm() {
      //重置
      this.defaulData = [];
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields(); //重置输入框提示
      });
    },
    tableDatalist() {
      //部门列表-表格列表
      let obj = { domainId: this.$route.query.domainId }; //获取url域domainId
      StaffDepartmentListApi(obj).then((response) => {
        if (response.data) {
          this.tableData = response.data;
          this.sortTableData(this.tableData);
        }
      });
    },
    sortTableData(arr) {
      //递归排序
      if (arr.length) {
        arr.forEach((item) => {
          item.displayOrderNumber = item.displayOrder;
          if (item.children.length) {
            this.sortTableData(item.children);
          }
        });
      }
      console.log(this.tableData);
    },
    approveOrgTableList() {
      //列表表格-查询结果
      let obj2 = { domainId: this.$route.query.domainId };
      approveOrgTableListApi(this.params, obj2).then((response) => {
        if (response.data.data) {
          this.tableDataApprove = response.data.data;
          this.params.total = response.data.total;
          console.info("approve", response.data.data);
        }
      });
    },
    checkChange(key, data) {
      //selectTree组件-复选框选中的数据
      console.log(key);
      console.log(data);
      this.$set(this.params, "departIds", key);
    },
    handleCurrentChange(val) {
      //分页切换页码
      console.log(val);
      this.params.pageIndex = val;
      this.approveOrgTableList();
    },
    handleSizeChange(val) {
      //切换每页条数
      console.log(val);
      this.params.pageSize = val;
      this.approveOrgTableList();
    },
    handleSelectionChange(val) {
      //选中全选
      console.log(val);
      this.multipleSelection = val;
    },
    handleSelectionAllChange(selection, first) {
      //全选
      if (!first) {
        this.isAllSelect = !this.isAllSelect;
      }
      selection.map((el) => {
        if (el.children) {
          el.children.map((j) => {
            this.toggleSelection(j, this.isAllSelect);
          });
          if (el.children.length > 0) {
            this.handleSelectionAllChange(el.children, true);
          }
        }
      });
    },
    toggleSelection(row, select) {
      //全选选中与取消选中
      if (select) {
        this.$refs.districtTable.toggleRowSelection(row, select); //全选选中
      } else {
        this.$refs.districtTable.clearSelection(); //取消选中
      }
    },
    addDept() {
      //新增
      this.showdialog = true;
      this.$refs.popChildren.getTableRow({}, 0);
    },
    editStaff(row) {
      //编辑
      this.StaffBoxFlag = false;
      this.staffinfo = row;
    },
    ApprovedOrgBtn(row) {
      this.$refs.approveRef.showModal(row);
      //删除
      //删除选中表格数据
      // let id = row.id;
      // // let obj2={domainId:this.$route.query.domainId}//获取url域domainId
      // if (Object.keys(row) != "") {
      //   this.$confirm("审批通过该公司, 是否继续?", "提示", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning",
      //   })
      //     .then(() => {
      //       ApprovedOrgBtnApi(id).then(() => {
      //         this.approveOrgTableList(); //表格列表
      //       });
      //     })
      //     .catch(() => {
      //       // this.radio = ""; //清空选中
      //     });
      // }
    },
    patchDel() {
      //批量删除
      let obj2 = { domainId: this.$route.query.domainId }; //获取url域domainId
      if (this.multipleSelection.length) {
        this.$confirm("此操作将永久删除此对应数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            let ids = [];
            this.multipleSelection.forEach((item) => {
              ids.push(item.id);
            });
            delDepartmentsApi(ids, obj2).then(() => {
              this.tableDatalist(); //表格列表
            });
          })
          .catch(() => {
            // this.radio = ""; //清空选中
          });
      }
    },
    importEmployee() {
      this.showdialogImport = true;
    },
    moveDept() {
      this.showdialogMove = true;
      this.$refs.MovepopChildren.getTableRow(this.multipleSelection, 0);
    },
    ImDept() {
      this.showdialogIm = true;
      this.$refs.ImpopChildren.getTableRow(this.multipleSelection, 0);
    },
    close(row) {
      //关闭排序
      this.tableDatalist(); //表格列表
    },
    totalMemberClick(row) {
      //点击部门成员数弹窗
      this.showdialogUser = true;
      this.$refs.UserpopChildren.getTableRow(row, 0);
    },
    refurlist() {
      //弹窗后刷新列表
      this.search(); //表格列表
    },
    ApprovedOrgDetail(row) {
      //审批企业详情
      console.log("detail row", row);
      this.status = row.status;
      this.drawer = true;
      this.organizationId = row.id; //获取组织id
      this.companyName = row.name;
      let obj2 = { domainId: this.$route.query.domainId };
      console.info("before params", this.params.industryCode);
      !this.params.industryCode
        ? (this.params.industryCode = row.industryCode)
        : null;
      ApprovedOrgDetailApi(row, obj2).then((response) => {
        console.log("response1", response);
        this.formList = response.data || {};
      });
    },
  },
};
</script>
<style lang="scss">
.ContainerBox {
  .remarkBox {
    .remarkInfo {
      background: #fafafa;
      color: #666666;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      line-height: 30px;
      padding: 10px;
      display: flex;
      .el-icon-flag {
        margin-top: 9px;
        color: #ffc108;
        margin-right: 10px;
      }
    }
  }
  .rightBox {
    display: flex;
    justify-content: flex-end;
    .el-input {
      margin-right: 10px;
    }
  }
  .HighSearchBox {
    margin-top: 15px;
  }
  .primaryColor {
    color: #108ee9;
  }
  .dangerColor {
    color: red;
  }
  .bluelink {
    color: #409eff;
  }
  .TableSelectBox {
    display: flex;
    background: #e6f3fc;
    color: #666666;
    border: 1px solid #d4f0fc;
    border-radius: 4px;
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 5px 0;
    span {
      line-height: 20px;
      i {
        margin-left: 5px;
        margin-right: 5px;
        color: #2e8ad7;
      }
    }
  }
  .el-drawer__header {
    margin-bottom: 0 !important;
  }
  .el-drawer__header > :first-child {
    font-size: 16px;
  }
}

.displayOrderInput {
  display: flex;
  align-items: center;
  // .el-input{width: 80%;}
  i {
    margin-left: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}

.eldrawerSection {
  padding: 10px 30px;
  font-size: 14px;
  .el-form-item {
    display: flex;
    flex-direction: column;
  }
  .el-form-item__label {
    font-weight: bold;
    font-size: 14px;
  }
  .span-box {
    display: inline-block;
    position: relative;
    i {
      position: absolute;
      left: -15px;
      top: 11px;
      color: #0076f6;
    }
    strong {
      font-weight: bold;
      margin-left: 5px;
    }
  }
}
</style>
