<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="一级标题" prop="hzName">
        <el-input
          v-model="queryParams.hzName"
          placeholder="请输入一级标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['kaohe:gather:add']"
        >生成汇总</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['kaohe:gather:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['kaohe:gather:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['kaohe:gather:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="gatherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="一级标题" align="center" prop="hzName" min-width="200" :show-overflow-tooltip="true"/>
<!--      <el-table-column label="表头" align="center" prop="tableHeader" min-width="200" :show-overflow-tooltip="true"/>
      <el-table-column label="表数据" align="center" prop="tableData" min-width="200" :show-overflow-tooltip="true"/>-->
      <el-table-column label="备注" align="center" prop="remark" min-width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['kaohe:gather:edit']"
          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
          >汇总选项</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewKaoHeScore(scope.row)"
            v-hasPermi="['kaohe:gather:query']"
          >查看生成汇总
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['kaohe:gather:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生成汇总对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="99%" append-to-body top="15px !important">
      <div style="min-height: 400px">
        <recursive-tree
          style="margin-left: 0px"
          :node-data="treeData"
          :is-root="true"
          :is-disabled="optType===2"
          @add-child="handleAddChild"
          @remove-node="handleRemoveNode"
          @change-kaohe="changeKaoHe"
        ></recursive-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="optType===2">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择引用考核任务信息 -->
    <el-dialog title="引用考核任务选择" :visible.sync="khrw.open" width="900px">
      <div>
        <el-form :model="khrw.queryParams" :inline="true" label-width="100px">
          <el-form-item label="考核任务名称" prop="pcTitle" style="margin-bottom: 10px">
            <el-input
              v-model="khrw.queryParams.pcTitle"
              placeholder="请输入考核任务名称"
              clearable
              @keyup.enter.native="khrwQuery"
            />
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <el-button type="primary" icon="el-icon-search" size="small" @click="khrwQuery">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-table border v-loading="khrw.loading" :data="khrw.list" @row-dblclick="khrwRowChange">
          <el-table-column label="主键" align="center" prop="id" width="60px"/>
          <el-table-column label="考核任务名称" align="center" prop="pcTitle" min-width="150" :show-overflow-tooltip="true"/>
          <el-table-column label="考核任务描述" align="center" prop="pcDescription" min-width="150" :show-overflow-tooltip="true"/>
          <el-table-column label="模板名称" align="center" prop="templateName" min-width="120" :show-overflow-tooltip="true"/>
          <el-table-column label="考核任务备注" align="center" prop="remark" min-width="150" :show-overflow-tooltip="true"/>
        </el-table>
        <pagination
          v-show="khrw.total>0"
          :total="khrw.total"
          :page.sync="khrw.queryParams.pageNum"
          :limit.sync="khrw.queryParams.pageSize"
          @pagination="khrwQuery"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="khrwCancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <!--查看生成汇总-->
    <el-dialog title="查看生成汇总" :visible.sync="khdf.open" width="90%" top="20px !important">
      <div style="margin-bottom: 10px;">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="schzExport"
          v-hasPermi="['kaohe:gather:export']"
        >导出</el-button>
      </div>
      <el-table border :data="khdf.list" height="650px">
        <template v-for="column in khdf.tableHeader">
          <table-column :key="column.label" :column="column" />
        </template>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="khdf.open=false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listGather, getGather, delGather, addGather, updateGather } from "@/api/kaohe/gather"
import { listPingce } from "@/api/kaohe/pingce"
import TableColumn from '@/components/TableColumn'
import RecursiveTree from '@/components/RecursiveTree'

export default {
  name: "Gather",
  components: { TableColumn, RecursiveTree },
  data() {
    return {
      // 考核得分
      khdf:{
        open: false,
        id: null,
        hzName: null,
        list: [],
        tableHeader: []
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生成汇总表格数据
      gatherList: [],
      // 弹出层标题
      title: "",
      // 操作类型 1 新增    2  查看
      optType: 1,
      // 是否显示弹出层
      open: false,
      treeData: {
        title: '',
        data: [],
        code: '根',
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hzName: null
      },
      /** 选择引用考核任务*/
      khrw: {
        parentNode: null,
        // 是否显示弹出层
        open: false,
        // 列表遮罩层
        loading: false,
        // 列表查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          pcTitle: null,
        },
        // 表格数据
        list: [],
        // 总条数
        total: 0,
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询生成汇总列表 */
    getList() {
      this.loading = true
      listGather(this.queryParams).then(response => {
        this.gatherList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.treeData = {
        title: '',
        data: [],
        code: '根',
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true
      this.optType = 1;
      this.title = "添加生成汇总"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGather(id).then(response => {
        this.treeData = JSON.parse(response.data.titleStr)
        this.open = true;
        this.optType = 2;
        this.title = "查看汇总选项"
      })
    },
    /** 提交按钮 */
    submitForm() {
      let obj={flag: true}
      if(this.treeData.title===''||this.treeData.title===null){
        obj.flag = false;
        this.$alert(`【根】标题不能为空！`, `提示`, {
          type: 'Danger'
        })
      } else if(this.treeData.data && this.treeData.data.length<1 ){
        obj.flag = false;
        this.$alert(`【根】级节点的子级不能为空，请添加子级节点！`, `提示`, {
          type: 'Danger'
        })
      }
      if(this.treeData.data && this.treeData.data.length>0){
        let list = this.treeData.data;
        let sumZb = 0
        for (let i=0; i<list.length; i++){
          if(list[i].zb){
            sumZb += list[i].zb
          }
          if(list[i].type1==='0' && (list[i].title==='' || list[i].title===null) ){
            this.$alert(`【${list[i].code}】标题不能为空`, `提示`, {
              type: 'Danger'
            })
            obj.flag = false;
            break;
          }
          if(list[i].type1!=='0' && (list[i].title==='' || list[i].title===null) ){
            this.$alert(`【${list[i].code}】引用考核任务不能为空`, `提示`, {
              type: 'Danger'
            })
            obj.flag = false;
            break;
          }
          if(list[i].data && list[i].data.length < 1){
            this.$alert(`【${list[i].code}】的子级不能为空，请添加子级节点！`, `提示`, {
              type: 'Danger'
            })
            obj.flag = false;
            break;
          }
          if(i===(list.length-1) && sumZb!==1){
            this.$alert(`【根】评分占比合计不等于1，请检查修改！`, `提示`, {
              type: 'Danger'
            })
            obj.flag = false;
            break;
          }
          if(list[i].data && list[i].data.length > 0){
            this.msgFun(list[i].data,list[i].code,obj);
          }
        }
      }
      if(obj.flag){
        addGather(JSON.stringify(this.treeData)).then(response => {
          this.$modal.msgSuccess("新增成功")
          this.open = false
          this.getList();
        })
      }
    },
    msgFun(children, pNodeName, objFlag){
      let list = children;
      let sumZb = 0
      for (let i=0; i<list.length; i++) {
        if (list[i].zb) {
          sumZb += list[i].zb
        }
        if (list[i].type1 === '0' && (list[i].title === '' || list[i].title === null)) {
          this.$alert(`【${list[i].code}】标题不能为空`, `提示`, {
            type: 'Danger'
          })
          objFlag.flag = false;
          break;
        }
        if (list[i].type1 !== '0' && (list[i].title === '' || list[i].title === null)) {
          this.$alert(`【${list[i].code}】引用考核任务不能为空`, `提示`, {
            type: 'Danger'
          })
          objFlag.flag = false;
          break;
        }
        if (list[i].data && list[i].data.length < 1) {
          this.$alert(`【${list[i].code}】的子级不能为空，请添加子级节点！`, `提示`, {
            type: 'Danger'
          })
          objFlag.flag = false;
          break;
        }
        if (i === (list.length - 1) && sumZb !== 1) {
          this.$alert(`【${ pNodeName }】评分占比合计不等于1，请检查修改！`, `提示`, {
            type: 'Danger'
          })
          objFlag.flag = false;
          break;
        }
        if(list[i].data && list[i].data.length > 0){
          this.msgFun(list[i].data,list[i].code, objFlag);
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return delGather(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('kaohe/gather/export', {
        ...this.queryParams
      }, `gather_${new Date().getTime()}.xlsx`)
    },
    handleAddChild(parentNode,type1) {
      if (!parentNode.data) {
        this.$set(parentNode, 'data', [])
      }
      let code = 'N' + new Date().getTime();

      if(type1==='0'){
        parentNode.data.push({
          code: code,
          type1: type1,
          type: '0',
          title: null,
          id: null,
          zb: null,
          pcTitle: null,
          data: []
        })
      }
      if(type1==='1'){
        parentNode.data.push({
          code: code,
          type1: type1,
          type: '1',
          title: null,
          id: null,
          zb: null,
          pcTitle: null
        })
      }
      if(type1==='2'){
        parentNode.data.push({
          code: code,
          type1: type1,
          type: '1',
          title: null,
          id: null,
          pcTitle: null
        })
      }

    },
    handleRemoveNode(nodeToRemove) {
      const removeNode = (parent, node) => {
        if (parent.data) {
          const index = parent.data.indexOf(node)
          if (index !== -1) {
            parent.data.splice(index, 1)
          } else {
            parent.data.forEach(child => removeNode(child, node))
          }
        }
      }
      removeNode(this.treeData, nodeToRemove)
    },
    changeKaoHe(parentNode){
      this.khrw.parentNode = parentNode;
      this.khrw.open = true;
      this.khrw.queryParams.pageNum = 1;
      this.khrwQuery();
    },
    /** 引用考核任务信息列表查询 */
    khrwQuery() {
      this.khrw.loading = true;
      listPingce(this.khrw.queryParams).then(response => {
        this.khrw.list = response.rows;
        this.khrw.total = response.total;
        this.khrw.loading = false;
      });
    },
    /** 引用考核任务信息选择弹出框关闭*/
    khrwCancel() {
      this.khrw.open = false
    },
    // 引用考核任务选择 选中数据
    khrwRowChange(row) {
      this.khrw.parentNode.id = row.id;
      this.khrw.parentNode.title = row.pcTitle;
      this.khrw.parentNode.pcTitle = row.pcTitle;
      this.khrw.open = false;
    },
    // 查看生成汇总
    viewKaoHeScore(row){
      this.khdf.id = row.id;
      this.khdf.hzName = row.hzName;
      this.khdf.list = [];
      this.khdf.tableHeader = [];
      this.khdf.open = true;
      this.reset()
      getGather(row.id).then(response => {
        console.log(JSON.parse(response.data.tableData), JSON.parse(response.data.tableHeader));
        let khdfList = JSON.parse(response.data.tableData);
        let btTabelTree = JSON.parse(response.data.tableHeader);
        /*khdfList.forEach(item=> {
          item[btTabelTree[0].name]['khdx'] = item.khdx;
        })*/
        this.khdf.list = khdfList;

        btTabelTree.forEach(item => {
          item.prop = item.name;
          if(item.children && item.children.length>0){
            this.setProp(item.children, item.prop)
          }
        })
        this.khdf.tableHeader = btTabelTree;
      })
    },
    // 递归函数 设置prop参数
    setProp(list, prop){
      list.forEach(item=>{
        if(prop){
          item.prop = prop+'.'+item.name;
        }else {
          item.prop = item.name;
        }
        if(item.children && item.children.length>0){
          this.setProp(item.children, item.prop)
        }
      })
    },
    // 生成汇总导出
    schzExport(){
      this.download('kaohe/gather/export?id='+this.khdf.id, {}, `${ this.khdf.hzName+''+new Date().getTime()}.xlsx`)
    }
  }
}
</script>
