<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        v-model="form"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        :before-open="handleOpenBefore"
        :before-close="addClose"
        @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="areaCodesDataForm">
          <el-cascader :key="cascaderKey" v-model="form.areaCodesData" :options="treeList" :props="cascaderProps" clearable collapse-tags></el-cascader>
        </template>
        <!-- 区域搜索 -->
        <template slot="areaCodesSearch">
          <el-cascader v-model="searchFormAreaCodes" :options="treeList" :key="cascaderKey" collapse-tags :props="searchCascaderProps" clearable></el-cascader>
        </template>
        <template slot="menuLeft">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="addClick">新增</el-button>
        </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-edit" @click="updateTy(scope.row, scope.index)">停用 </el-button>
          <el-button v-if="scope.row.enableFlag == 1" type="text" size="small" icon="el-icon-edit" @click="updateQy(scope.row, scope.index)">启用 </el-button>
        </template>
        <template slot="extDrugEntForm" slot-scope="scope">
          <avue-select v-model="extDrugEnt" :dic="extDrugEntOptions" :props="extDrugEntProps" multiple placeholder="请选择服务上级组织" />
        </template>
        <template slot="subjectTypeAndChannelValueForm" slot-scope="scope">
          <el-radio-group v-model="subjectTypeAndChannelValue" class="w100">
            <el-radio :label="0">中金</el-radio>
            <el-radio :label="1">平安银行</el-radio>
          </el-radio-group>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog :visible.sync="addDialog">
      <div class="add-dialog">
        <div @click="changeAgentType('AT')">区域>></div>
        <div @click="changeAgentType('AE')">服务供应商>></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {fetchList, getObj, addObj, putObj, delObj, getListDrugEntOrAgent} from '@/api/wmmanagement';
import {tableOption, teamTableOption} from '@/const/crud/wmmanagement';
import {mapGetters} from 'vuex';
import {getObjDept, fetchTreeAddUser, getDeptBuildNameById, settleConfig} from '@/api/admin/dept';
import {getSubList, saveSettleConfig, updateSubLimitAmount} from '@/api/admin/deptSub';
import {saves} from '@/api/wmdadrugent';
import {getDictType} from '@/api/common';
import store from '@/store';
import {filterCodes, extractPaths} from '@/util/treeUtils.js';
import {getAreaTreeApi} from '@/api/areaTree';

export default {
  name: 'wmmanagement',
  data() {
    return {
      treeList: [],
      cascaderProps: {
        multiple: true,
        label: 'name',
        value: 'id'
      },
      cascaderKey: 0,
      addDialog: false,
      agentType: '',
      searchForm: {},
      searchFormAreaCodes: [],
      searchCascaderProps: {
        checkStrictly: true,
        label: 'name',
        value: 'id'
      },
      tableData: [],
      form: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      extDrugEnt: [], // 服务上级组织
      extDrugEntOptions: [], // 服务上级组织options
      extDrugEntProps: {
        label: 'name',
        value: 'value'
      },
      dialogType: 'add',
      showAddDialog: false
    };
  },
  created() {
    this.getAreaTree();
  },
  mounted() {
    // this.getInvoiceList();
  },
  computed: {
    ...mapGetters(['permissions', 'userInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.admin_wmdaagent_add, true),
        // delBtn: this.vaildData(this.permissions.admin_wmdaagent_del, false),
        editBtn: this.vaildData(this.permissions.admin_wmdaagent_edit, true)
      };
    }
  },
  watch: {
    'form.qylx': function(val, oldVal) {
      if (this.agentType === 'AE') {
        if ('' != val) {
          var obj = tableOption;
          let index = tableOption.column.findIndex(item => item['label'] === '服务上级组织');
          obj.column[index].addDisplay = false;
          if (val == 0) {
            obj.column[index].addDisplay = true;
            obj.column[index].editDisplay = true;
          } else {
            obj.column[index].addDisplay = false;
            obj.column[index].editDisplay = false;
          }
        }
      } else {
        if ('' != val) {
          var obj = teamTableOption;
          let index = teamTableOption.column.findIndex(item => item['label'] === '服务上级组织');
          obj.column[index].addDisplay = false;
          if (val == 0) {
            obj.column[index].addDisplay = true;
            obj.column[index].editDisplay = true;
          } else {
            obj.column[index].addDisplay = false;
            obj.column[index].editDisplay = false;
          }
        }
      }
    },
    extDrugEnt() {
      if (Array.isArray(this.extDrugEnt) && this.extDrugEnt.length === 0) {
        this.form.extDrugEnt = '';
      } else {
        this.form.extDrugEnt = this.extDrugEnt;
      }
      this.form.temp1 = this.extDrugEnt && this.extDrugEnt.join(',');
    }
  },
  methods: {
    // 获取区域树列表
    async getAreaTree() {
      const res = await getAreaTreeApi();
      this.treeList = res.data.data;
    },
    addClick() {
      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) {
      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;
      }
      this.agentType = row.agentType;
      if (row.agentType === 'AT') {
        this.tableOption = teamTableOption;
        this.$forceUpdate();
      }
      this.$refs.crud.rowEdit(row, index);
    },

    getList(page, params) {
      this.tableLoading = true;
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          let answer = response.data.data.records;
          answer.forEach(item => {
            if (item.deptPermissions && item.deptPermissions.length > 1) {
              item.deptPermissions = item.deptPermissions.sort((a, b) => a - b);
            }
            if (item.provAbbr) {
              item.provAbbrList = item.provAbbr.split(',');
            }
          });
          this.tableData = answer;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .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;
      }
      if (undefined != row.extDrugEnt && row.extDrugEnt.length > 0) {
        row.extDrugEnt = row.extDrugEnt.join(',');
      } else {
        row.extDrugEnt = null;
      }
      let params = Object.assign({}, row);
      params.provAbbr = params.provAbbrList.join(',');
      putObj(params)
        .then(data => {
          this.$message.success('修改成功');
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    handleSave: function(row, done, loading) {
      const flattenedArray = this.form.areaCodesData.flat();
      const areaCodes = Array.from(new Set(flattenedArray));
      row.areaCodes = areaCodes;
      if (undefined != row.sbjnzm && row.sbjnzm.length > 0) {
        row.sbjnzm = row.sbjnzm.join(',');
      } else {
        row.sbjnzm = null;
      }
      if (undefined != row.extDrugEnt && row.extDrugEnt.length > 0) {
        row.extDrugEnt = row.extDrugEnt.join(',');
      } else {
        row.extDrugEnt = null;
      }
      row.agentType = this.agentType;
      let params = Object.assign({}, row);
      params.provAbbr = params.provAbbrList.join(',');
      addObj(params)
        .then(data => {
          this.$message.success('添加成功');
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    searchReset() {
      ++this.cascaderKey;
      this.searchFormAreaCodes = [];
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchChange(form, done) {
      this.searchForm = form;
      if (this.searchFormAreaCodes.length) {
        const flattenedArray = this.searchFormAreaCodes.flat();
        const areaCodes = Array.from(new Set(flattenedArray));
        this.searchForm.areaCodes = areaCodes[areaCodes.length - 1];
      }
      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();
        });
    },
    handleOpenBefore(show, type) {
      this.$nextTick(() => {
        const rowData = this.$refs.crud.$refs.dialogForm.value;
        // 查询'服务上级组织'列表
        getListDrugEntOrAgent({deptLevel: rowData.deptLevel}).then(res => {
          this.extDrugEntOptions = res.data.data;
        });

        if (['edit', 'views'].includes(type)) {
          this.extDrugEnt = [];
          this.form.temp1 = '';
          const extDrugEntList = (rowData.extDrugEnt && rowData.extDrugEnt.split(',')) || [];
          for (let i = 0; i < extDrugEntList.length; i++) {
            this.extDrugEnt[i] = extDrugEntList[i];
          }
        } else if (type === 'add') {
          this.extDrugEnt = [];
          this.form.temp1 = '';
        }
      });
      show();
    }
  }
};
</script>
<style lang="scss" scoped>
.add-dialog div {
  cursor: pointer;
  color: #333;
  margin: 20px auto;
  text-align: center;
  &:hover {
    color: #999;
  }
}
</style>
