<template>
  <div class="app-container">
    <Form :formList="formList" :ruleFormData="ruleForm" @fnClick="callback"></Form>
    <!--    弹窗  -->
    <el-dialog title="选择包含资源" :visible.sync="open" width="1000px" height="300px" append-to-body>
      <el-tabs v-model="activeName" @tab-click="handleClick(1)">
        <el-tab-pane label="按业务名称选择" name="first"></el-tab-pane>
        <el-tab-pane label="按逻辑节点标识选择" name="second"></el-tab-pane>
      </el-tabs>
      <el-row :gutter="20">
        <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
          <pane size="20">
            <el-col>
              <div class="head-container">
                <el-tree v-if="treeShow" :data="deptOptions" :props="defaultProps" :current-node-key="currentNodeKey" :expand-on-click-node="false" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
              </div>
            </el-col>
          </pane>
          <pane size="80">
            <div class="block" style="max-height: calc(100vh - 290px);overflow: auto;">
              <TableList ref="tabRef" :columns="columns" :config="{colTopHiddenIcon: true}" :queryParams="{total: 0}" :tableList="tableList" @fnClick="callback"></TableList>
            </div>
          </pane>
        </splitpanes>
      </el-row>
      <div style="text-align: right;margin-right: 20px;margin-top: 20px;">
        <el-button type="primary" style="margin-left: 10px;" @click="submitPubilc">确定</el-button>
        <el-button @click="open = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
  import Form from '@/components/form/index.vue';
  import TableList from "@/components/table/index.vue"
  import { Splitpanes, Pane } from "splitpanes"
  import {listAllBusinessList, addTaskStatic, switchNameTree} from "@/api/disRevenue/earnManage"
  import {getLogicalNode, getRegistList} from "@/api/disRevenue/resource"
  import "splitpanes/dist/splitpanes.css"
  export default {
    name: 'busValueCount_Details',
    components: {Form, TableList, Splitpanes, Pane},
    dicts: ['resource_type', 'caculate_type'],
    data() {
      return {
        activeName: 'first',
        // 所有树选项
        deptOptions: undefined,
        defaultProps: {
          children: "children",
          label: "label"
        },
        ruleForm: {},
        formList: [],
        switchNameList: [],
        paramsData: {},
        busNameList: {},
        open: false,
        busNameListData: [],
        logicalNodeList: [],
        currentNodeKey: '',
        tableColChange: {},
        submitChangeVal: {},
        changeName: null,
        treeShow: false,
        tableList: [],
        // 列显隐信息
        columns: {
          id: { label: `ID`,width: '50'},
          clientId: { label: `ClientID`, minWidth: '200', visible: true },
          businessName: { label: `业务名称`,minWidth: '200',visible: true},
          logicalNodeId: { label: `逻辑节点标识`,minWidth: '320',visible: true},
        },
      }
    },
    created() {
      this.paramsData = this.$route && this.$route.query;
      this.fnFormList();
      this.switchList();
      this.fnLogicalNode();
    },
    methods: {
      handleClick(num) {
        this.treeShow = false;
        setTimeout(() => {
          this.treeShow = true;
        },100);
        if (this.$refs.tabRef) {
          this.$refs.tabRef.selectList = [];
        }
        if (num && num === 1) {
          this.tableColChange = {};
        } else if (this.submitChangeVal && this.submitChangeVal.activeName) {
          this.tableColChange = this.submitChangeVal && this.submitChangeVal.content && Object.keys(this.submitChangeVal.content).length > 0 ? this.submitChangeVal.content : {};
          this.activeName = this.submitChangeVal.activeName;
        }
        this.deptOptions = null;
        this.currentNodeKey = '';
        if (this.activeName === 'first') {
          this.deptOptions = this.busNameListData;
        } else {
          this.deptOptions = this.logicalNodeList;
        }
        if (this.deptOptions.length > 1) {
          this.changeName = null;
          this.currentNodeKey = this.deptOptions[0].id;
          this.handleNodeClick(this.deptOptions[0]);
        }
      },
      // 逻辑节点标识
      fnLogicalNode() {
        getLogicalNode().then(val => {
          if (val && val.length > 0) {
            val.push({logicalNodeId: '空标识'});
            this.logicalNodeList = val && val.map(item => {
              return Object.assign({}, item,{label: item.logicalNodeId, id: item.logicalNodeId});
            });
          }
        });
      },
      // 节点单击事件
      handleNodeClick(data) {
        if (this.changeName) {
          this.removeDup();
        }
        let params = {};
        if (this.activeName === 'first') {
          if (data.id === '空标识') {
            params = {businessEmpty: true};
          } else {
            params = {businessName: data.id};
          }
        } else {
          if (data.id === '空标识') {
            params = {logicalNodeEmpty: true};
          } else {
            params = {logicalNodeId: data.id};
          }
        }
        this.changeName = data.id;
        this.getList(params,data.id);
      },
      //  去重复
      removeDup() {
        if (this.$refs.tabRef.selectList.length > 0) {
          if (this.tableColChange[this.changeName] && this.tableColChange[this.changeName].length > 0) {
            let newArr = [];
            this.$refs.tabRef.selectList.forEach(item => {
              let index = 0;
              this.tableColChange[this.changeName].some(val => {
                if (item.id === val.id) {
                  index = 1;
                  return true;
                }
              });
              if (index === 0) {
                newArr.push(item);
              }
            });
            this.tableColChange[this.changeName] = this.tableColChange[this.changeName].concat(newArr);
          } else {
            this.tableColChange[this.changeName] = this.$refs.tabRef.selectList;
          }
          this.$refs.tabRef.selectList = [];
        } else {
          this.tableColChange[this.changeName] = {};
        }
      },
      getList(val,changeVal) {
        this.$modal.loading();
        getRegistList(Object.assign({}, {resourceType: 1}, val)).then(val => {
          this.tableList = val && val.data || [];
          if (this.tableColChange[changeVal] && this.tableColChange[changeVal].length > 0) {
            setTimeout(() => {
              this.$refs.tabRef.defaultSelectRowsAll(null, this.tableColChange[changeVal]);
            },500);
          }
          this.$modal.closeLoading();
        }).catch(() => {
          this.$modal.closeLoading();
        });
      },
      // formList集合
      fnFormList(objVal) {
        this.formList = [{
          config: {title: '基本信息'},
          controls: {
            id: {label: 'ID',hidden: true},
            taskName: {label: '任务名称', span: 18, type: 'input',required: true},
            businessName: {label: '业务名称', span: 18, type: 'select', options:[]},
            resourceType: {label: '包含资源类型', span: 18, type: 'select', eventName: 'change', options: this.dict.type.resource_type, required: true},
            includedResourcesTree: {label: '包含资源', span: 18, type: 'input', required: true, hidden: this.ruleForm.resourceType && this.ruleForm.resourceType === '1' ? false : true},
            changeClientId: {label: '选择ClientID', span: 3, type: 'button', eventName: 'change', hidden: this.ruleForm.resourceType && this.ruleForm.resourceType === '1' ? false : true},
            includedResources: {label: '包含资源', span: 18, type: 'cascader', options: [], required: true, hidden: this.ruleForm.resourceType && this.ruleForm.resourceType === '2' ? false : true},
            calculationType: {label: '计算类型', span: 18, type: 'select', options: this.dict.type.caculate_type, eventName: 'change', required: true},
            startTime: {label: '时间段', span: 18, type: 'month', hidden: this.ruleForm.calculationType && this.ruleForm.calculationType === '2' ? false : true},
            endTime: {label: '时间段', span: 18, type: 'datetimerange', hidden: this.ruleForm.calculationType && this.ruleForm.calculationType === '1' ? false : true},
          }
        }];
      },
      switchList() {
        listAllBusinessList().then(val => {
          let sideBus = [];
          this.formList[0].controls.businessName['options'] = val && val.data.map(item => {
            sideBus.push(Object.assign({}, item, {id: item.businessName, label: item.businessName}));
            this.busNameList[item.businessName] = item;
            return Object.assign({label: item.businessName, value: item.businessName});
          });
          sideBus.push({label: '空业务', id: '空标识'});
          this.busNameListData = sideBus;
        });
      },
      // 包含资源
      includeDataList(num) {
        if (num === '1') {
          getRegistList({resourceType: 1}).then(val => {
            this.formList[0].controls.includedResourcesTree['options'] = val && val.data.map(item => {
              return Object.assign({label: item.clientId, id: item.clientId});
            });
          });
        } else {
          this.$modal.loading();
          switchNameTree().then(val => {
            this.switchNameList = val && val;
            this.formList[0].controls.includedResources['options'] = val && val.data;
            this.$modal.closeLoading();
          }).catch(() => {
            this.$modal.closeLoading();
          });
        }
      },
      submitPubilc() {
        this.removeDup();
        this.open = false;
        this.treeShow = false;
        let valList = [];
        if (Object.keys(this.tableColChange).length > 0) {
          this.submitChangeVal = {activeName: this.activeName, content: this.tableColChange};
          Object.keys(this.tableColChange).forEach(key => {
            if (this.tableColChange[key] && this.tableColChange[key].length > 0) {
              valList = valList.concat(this.tableColChange[key].map(item => item.clientId));
            }
          });
        } else {
          this.submitChangeVal = {activeName: 'first'};
        }
        this.$set(this.ruleForm, 'includedResourcesTree', valList.toString());
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'resourceType':
              if (dataVal) {
                if (dataVal === '1') {
                  this.formList[0].controls.includedResourcesTree['hidden'] = false;
                  this.formList[0].controls.changeClientId['hidden'] = false;
                  this.formList[0].controls.includedResources['hidden'] = true;
                } else if (dataVal === '2') {
                  this.formList[0].controls.includedResources['hidden'] = false;
                  this.formList[0].controls.includedResourcesTree['hidden'] = true;
                  this.includeDataList(dataVal);
                }
              } else {
                this.formList[0].controls.includedResourcesTree['hidden'] = true;
                this.formList[0].controls.changeClientId['hidden'] = true;
                this.formList[0].controls.includedResources['hidden'] = true;
              }
              // if (dataVal) {}
              // this.includeDataList(dataVal);
              break;
            case 'calculationType':
              if (dataVal) {
                if (dataVal === '1') {
                  this.formList[0].controls.startTime['hidden'] = true;
                  this.formList[0].controls.endTime['hidden'] = false;
                } else if (dataVal === '2') {
                  this.formList[0].controls.startTime['hidden'] = false;
                  this.formList[0].controls.endTime['hidden'] = true;
                }
              } else {
                this.formList[0].controls.startTime['hidden'] = true;
                this.formList[0].controls.endTime['hidden'] = true;
              }
              break;
            case 'changeClientId':
              this.open = true;
              this.treeShow = true;
              this.handleClick();
              break;
            case 'submit':
              dataVal['calculationMode'] = this.paramsData.calculationMode;
              if (dataVal.includedResources) {
                let newArr = [];
                dataVal.includedResources.forEach(item => {
                  newArr.push(item[1]);
                });
                dataVal.includedResources = newArr.toString();
              }
              if (dataVal.includedResourcesTree) {
                dataVal.includedResources = dataVal.includedResourcesTree;
                delete dataVal.includedResourcesTree;
              }
              if (dataVal && dataVal.businessName) {
                dataVal['businessCode'] = this.busNameList[dataVal.businessName].id;
              }
              if (dataVal && dataVal.endTime) {
                dataVal.startTime = dataVal.endTime[0];
                dataVal.endTime = dataVal.endTime[1];
              }
              addTaskStatic(dataVal).then(response => {
                this.$modal.msgSuccess(response.msg);
                this.$router.push("/earnManage/busValueCount");
              }).catch(() => {
                this.$modal.msgError("操作失败")
              });
              break;
            case 'cancel':
              this.$router.push("/earnManage/busValueCount");
              break;
            default:
          }
        }
      }
    }
  }
</script>
<style>
</style>
