<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        :before-close="addClose"
        v-model="form"
        :search="searchForm"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @search-reset="searchReset"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
      >
        <template slot="menuLeft">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="addClick"
            >新增</el-button
          >
        </template>
        <template slot="deptIdForm" slot-scope="scope">
          <avue-input-tree
            v-model="scope.row.deptId"
            :node-click="getNodeData"
            :dic="treeDeptData"
            :props="defaultProps"
            placeholder="请选择所属部门"
          />
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            v-if="scope.row.enableFlag == 0"
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="aditClick(scope.row, scope.index)"
            >编辑
          </el-button>
          <el-button
            v-if="scope.row.enableFlag == 0"
            type="text"
            size="small"
            icon="el-icon-lock"
            @click="updateTy(scope.row, scope.index)"
            >停用
          </el-button>
          <el-button
            v-if="scope.row.enableFlag == 1"
            type="text"
            size="small"
            icon="el-icon-unlock"
            @click="updateQy(scope.row, scope.index)"
            >启用
          </el-button>
          <el-button
            v-if="scope.row.deptLevel == 4"
            type="text"
            size="small"
            icon="el-icon-c-scale-to-original"
            @click="ratingFn(scope.row, scope.index)"
            >评分
          </el-button>
          <el-button
            v-if="scope.row.deptLevel == 4"
            type="text"
            size="small"
            icon="el-icon-document"
            @click="riskInquiryFn(scope.row, scope.index)"
            >风险查询
          </el-button>
          <el-button
            v-if="scope.row.deptLevel == 4"
            type="text"
            size="small"
            icon="el-icon-document"
            @click="servicePackageMonitoringDetail(scope.row, scope.index)"
            >服务商合规体系
          </el-button>
          <el-button
            v-if="false"
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="permissionsShow(scope.row, scope.index)"
            >权限
          </el-button>
        </template>
        <!-- 区域搜索 -->
        <template slot="areaCodesSearch">
          <el-cascader
            v-model="searchFormAreaCodes"
            :options="treeList"
            :key="cascaderKey"
            collapse-tags
            :props="searchCascaderProps"
            clearable
          ></el-cascader>
        </template>
        <!-- 表单-区域 -->
        <template slot="areaCodesDataForm">
          <el-cascader
            :key="cascaderKey"
            v-model="form.areaCodesData"
            :options="treeList"
            collapse-tags
            :props="cascaderProps"
            clearable
          ></el-cascader>
        </template>
      </avue-crud>

      <el-dialog :visible.sync="addDialog">
        <div class="add-dialog">
          <div @click="changeAgentType('AT')">区域/服务供应商团队>></div>
          <div @click="changeAgentType('AE')">区域/服务供应商公司>></div>
        </div>
      </el-dialog>

      <el-dialog
        center
        title="设置"
        :visible.sync="permissionsVisible"
        width="45%"
        :before-close="permissionsClose"
      >
        <el-form ref="permissionsForm" :model="form" label-width="80px">
          <el-form-item label="结算权限">
            <el-switch v-model="permissionsForm.mahSettleFlag"> </el-switch>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="permissionsClose">取 消</el-button>
          <el-button type="primary" @click="permissionsClick">确 定</el-button>
        </span>
      </el-dialog>
    </basic-container>
    <addDialog @addSuccess="addSuccess" ref="addDialogRef" />
    <ratingDialog @success="addSuccess" ref="ratingRef" />
    <servicePackageMonitoringDialog ref="servicePackageMonitoringRef" />
  </div>
</template>

<script>
import addDialog from "./components/addDialog.vue";
import ratingDialog from "./components/ratingDialog.vue";
import servicePackageMonitoringDialog from "./components/servicePackageMonitoringDialog.vue";

import {
  fetchList,
  selectDeptId1,
  getObj,
  addObj,
  putObj,
  delObj
} from "@/api/wmdaagent";
import { tableOption, teamTableOption } from "@/const/crud/wmdaagent";
import { mapGetters } from "vuex";
import { getAreaTreeApi } from "@/api/areaTree";
import {
  getObjDept,
  fetchTreeAddUser,
  getDeptBuildNameById,
  settleConfig
} from "@/api/admin/dept";
import { filterCodes, extractPaths } from "@/util/treeUtils.js";
export default {
  components: {
    addDialog,
    ratingDialog,
    servicePackageMonitoringDialog
  },
  name: "wmdaagent",
  data() {
    return {
      defaultProps: {
        label: "name",
        value: "id"
      },
      addDialog: false,
      agentType: "",
      entLevel: 0,
      searchForm: {},
      searchFormAreaCodes: [],
      searchCascaderProps: {
        multiple: true,
        label: "name",
        value: "id"
      },
      cascaderKey: 0,
      tableData: [],
      form: {
        areaCodesData: []
      },
      treeDeptData: [],
      extDrugEntId: "",
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      extDrugEntval: "",
      permissionsVisible: false,
      permissionsForm: {
        id: "",
        mahSettleFlag: false
      },
      treeList: [],
      cascaderProps: {
        multiple: true,
        label: "name",
        value: "id"
      }
    };
  },
  computed: {
    ...mapGetters(["permissions", "userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.admin_wmdaagent_add, false),
        delBtn: this.vaildData(this.permissions.admin_wmdaagent_del, false),
        editBtn: this.vaildData(this.permissions.admin_wmdaagent_edit, false)
      };
    }
  },
  mounted() {
    this.init();
    this.getObjDept1();
    this.getAreaTree();
  },
  methods: {
    servicePackageMonitoringDetail(row) {
      this.$refs.servicePackageMonitoringRef.getInfo(row.deptId);
    },
    // 风险查询
    riskInquiryFn(row) {
      this.$router.push({
        path: "/admin/wmdaagent/riskInquiry?id=" + row.zjNumber
      });
    },
    ratingFn(row) {
      this.$refs.ratingRef.showInfoFn(row);
    },
    // 获取区域树列表
    async getAreaTree() {
      const res = await getAreaTreeApi();
      this.treeList = res.data.data;
    },
    addClick() {
      this.$refs.addDialogRef.show(this.extDrugEntId);
      console.log("this.extDrugEntId", this.extDrugEntId);
      return;
      this.form.areaCodesData = [];
      this.addDialog = true;
    },
    changeAgentType(type) {
      this.addDialog = false;
      this.agentType = type;
      if (this.agentType === "AT") {
        this.tableOption = teamTableOption;
        this.$forceUpdate();
        this.$refs.crud.rowAdd();
      }
      this.$refs.crud.rowAdd();
    },
    addClose(done) {
      ++this.cascaderKey;
      this.tableOption = tableOption;
      this.agentType = "";
      this.$forceUpdate();
      done();
    },
    aditClick(row, index) {
      this.$refs.addDialogRef.editFn(row);
      return;
      const areaCodes = row.areaCodes;
      const treeList = JSON.parse(JSON.stringify(this.treeList));
      const currTree = filterCodes(areaCodes, treeList);
      if (currTree) {
        const ids = extractPaths(currTree);
        row.areaCodesData = ids;
      }
      if (row.agentType === "AT") {
        this.tableOption = teamTableOption;
        this.$forceUpdate();
      }

      this.$refs.crud.rowEdit(row, index);
    },
    showUplevel() {},
    init() {
      fetchTreeAddUser().then(response => {
        this.treeDeptData = response.data.data;
      });
    },
    nodeClick(data) {
      this.page.page = 1;
      this.getList(this.page, { deptId: data.id });
    },
    handleOpenBefore(show, type) {
      fetchTreeAddUser().then(response => {
        this.treeDeptData = response.data.data;
      });
    },
    handleDept() {
      fetchTreeAddUser().then(response => {
        this.treeDeptData = response.data.data;
      });
    },
    getNodeData() {
      fetchTreeAddUser().then(response => {
        this.treeDeptData = response.data.data;
      });
    },
    async getList(page, params) {
      this.tableLoading = true;
      // 先请求服务上级所有值接口
      await selectDeptId1().then(response => {
        if (response.data.data) {
          this.extDrugEntval = response.data.data[0].name;
          this.extDrugEntId = response.data.data[0].id;
        }
      });
      // 再请求list页面，给服务上级组织赋值
      await fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          let answer = response.data.data.records;
          this.tableData = answer;
          for (let i = 0; i < this.tableData.length; i++) {
            this.tableData[i].extDrugEnt = this.extDrugEntval;
          }
          this.page.total = response.data.data.total;
          this.tableLoading = false;
          this.showUplevel();
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    rowDel: function(row, index) {
      this.$confirm("是否确认删除ID为" + row.id, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delObj(row.id);
        })
        .then(data => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    handleUpdate: function(row, index, done, loading) {
      const flattenedArray = this.form.areaCodesData.flat();
      const areaCodes = Array.from(new Set(flattenedArray));
      row.areaCodes = areaCodes;
      row.updateUser = 0;
      if (undefined != row.sbjnzm && row.sbjnzm.length > 0) {
        row.sbjnzm = row.sbjnzm.join(",");
      } else {
        row.sbjnzm = null;
      }
      row.extDrugEnt = this.extDrugEntId;
      putObj(row)
        .then(data => {
          this.$message.success("修改成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    addSuccess() {
      this.getList(this.page);
    },
    handleSave: function(row, done, loading) {
      const flattenedArray = this.form.areaCodesData.flat();
      const areaCodes = Array.from(new Set(flattenedArray));
      row.areaCodes = areaCodes;
      row.updateUser = 0;
      if (this.entLevel > 3) {
        this.$message.error("二级代理商不能添加代理商");
        return false;
      }
      if (undefined != row.sbjnzm && row.sbjnzm.length > 0) {
        row.sbjnzm = row.sbjnzm.join(",");
      } else {
        row.sbjnzm = null;
      }
      row.extDrugEnt = this.extDrugEntId;
      row.agentType = this.agentType;
      addObj(row)
        .then(data => {
          this.$message.success("添加成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    searchReset() {
      this.searchFormAreaCodes = [];
      ++this.cascaderKey;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    extractLastElements(array) {
      // 创建一个新的空数组来存储结果
      let result = [];
      // 遍历输入的二维数组
      for (let i = 0; i < array.length; i++) {
        // 检查内部数组是否非空
        if (array[i].length > 0) {
          // 将内部数组的最后一个元素添加到结果数组中
          result.push(array[i][array[i].length - 1]);
        }
      }
      // 返回结果数组
      return result;
    },
    searchChange(form, done) {
      this.searchForm = form;
      if (this.searchFormAreaCodes.length) {
        const codes = this.extractLastElements(this.searchFormAreaCodes);
        this.searchForm.areaCodes = codes;
      }
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    refreshChange() {
      this.getList(this.page);
    },
    getObjDept1() {
      let deptId = this.userInfo.deptId;
      getObjDept(deptId)
        .then(data => {
          var deptInfo = data.data.data;
          this.entLevel = deptInfo.level;
        })
        .catch(() => {});
    },
    updateTy: function(row, index, done, loading) {
      row.enableFlag = "1";
      putObj(row)
        .then(data => {
          this.$message.success("停用成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    updateQy: function(row, index, done, loading) {
      row.enableFlag = "0";
      putObj(row)
        .then(data => {
          this.$message.success("启用成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    permissionsShow(row) {
      this.form.id = row.id;
      this.form.mahSettleFlag = row.mahSettleFlag;
      this.permissionsVisible = true;
    },
    permissionsClose() {
      this.permissionsVisible = false;
    },
    async permissionsClick() {
      if (this.form.mahSettleFlag === "") {
        this.$message.warning("请先选择结算权限！");
        return;
      }
      let res = await settleConfig(this.permissionsForm);
      if (res.data.code === 0) {
        this.$message.success("配置成功！");
        this.getList(this.page);
        this.permissionsVisible = false;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.add-dialog div {
  cursor: pointer;
  color: #333;
  margin: 20px auto;
  text-align: center;
  &:hover {
    color: #999;
  }
}
::v-deep .el-select {
  width: 100%;
}
</style>
