<template>
  <div style="display: flex;">
    <div style="width: 180px;height:520px;overflow: scroll;border: 1px solid;">
      <el-tree :data="patientRegister.customerOrgTreeAll" :props="customerOrg.treeprops" @node-click="handleNode" />
    </div>
    <div style="display: block;width:635px; margin-left: 5px;">
      <el-table :data="dataCusOrgOCX" border height="470" highlight-current-row @row-dblclick="rowDblclick" size="small">
        <el-table-column prop="customerOrgName" label="体检单位" width="150"/>
        <el-table-column prop="customerOrgId" label="次数" width="50" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.customerOrgRegister" placeholder="次数" style="width: 50px;" size="small"
              :disabled="!useCusOrg || scope.row.customerOrgId == dict.personOrgId"
              @change="changeMedicalTimes(scope.$index)" value-key="id">
              <el-option v-for="item in scope.row.customerOrgRegisterList" :key="item.id" :label="item.medicalTimes"
                :value="item" />
            </el-select>
          </template>
        </el-table-column>
        <!-- 
        <el-table-column prop="dateType" label="日期方式" width="85" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.dateType" placeholder="请选择" filterable clearable size="small">
              <el-option label="登记日期" value="creationTime" />
              <el-option label="体检日期" value="medicalStartDate" />
              <el-option label="总检日期" value="summaryDate" />
            </el-select>
          </template>
        </el-table-column>
        -->
        <el-table-column prop="startDate" label="起始日期" width="90" align="center">
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.startDate" type="date" placeholder="截止日期" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="截止日期" width="90" align="center">
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.endDate" type="date" placeholder="截止日期" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="customerOrgGroupIds" label="分组" width="200">
          <template slot-scope="scope">
            <el-select v-model="scope.row.customerOrgGroupIds" multiple collapse-tags filterable clearable
              style="width:196px;" placeholder="请选择分组" size="small" 
              @focus="getCustGroup(scope.$index, scope.row.customerOrgRegister.id)"
              :disabled="!useCusOrg || scope.row.customerOrgId == dict.personOrgId">
              <el-option v-for="item in scope.row.customerOrgGroupList" :key="item.value" :label="item.displayName"
                :value="item.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column min-width="30" align="center">
          <template slot-scope="scope">
            <i class="el-icon-delete" @click="dataCusOrgOCX.splice(scope.$index, 1)"
              style="font-size: 20px;color: red;cursor:pointer;"></i>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex;margin-top: 8px;margin-left: 15px;">
        <div style="display: block;">
          <div>
            <span>日期方式：</span>
            <el-radio-group v-model="dateType" @change="changeDateType">
              <el-radio label="creationTime">登记日期</el-radio>
              <el-radio label="medicalStartDate">体检日期</el-radio>
              <el-radio label="summaryDate">总检日期 </el-radio>
            </el-radio-group>
          </div>
          <div style="margin-top: 5px;">
            <span>单位作为查询条件：</span>
            <el-checkbox v-model="useCusOrg" @change="changeUseOrg" />
          </div>
        </div>
        <div style="margin-left: 150px;margin-top: 5px;">
          <el-button type="primary" @click="btnOk">确定</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import moment from "moment";
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { arrayExistObj } from "../../utlis/proFunc";
import { getTreePids, getTreeAllChildIdsById } from "../../utlis/tree";
export default {
  components: {},
  data() {
    return {
      preNodeId: '',  //上一次点击树节点
      curNodeId: '',  //本次点击树节点       
      dateType: 'creationTime',
      useCusOrg: true,   //是否使用单位
      //体检单位，体检次数，日期类型，起止日期，分组
      dataCusOrgOCX: [{
        id: '',    //随机的ID，用于删除
        customerOrgId: '',           //
        customerOrgName: '',         //企业名称，显示用
        customerOrgRegister: {},     //已选的体检次数
        customerOrgRegisterList: [], //当前单位的体检次数信息
        dateType: 'creationTime',  // 登记日期：creationTime；体检日期：medicalStartDate；总检日期：summaryDate
        startDate: '',
        endDate: '',
        customerOrgGroupIds: [],  //已选分组
        customerOrgGroupList: [],  //可选的分组
      }],
    };
  },
  //<el-tree :data="$store.state.customerOrg.customerOrgTree" :props="$store.state.customerOrg.treeprops" @node-click="treeclick"></el-tree>
  computed: {
    ...mapState(["dict", "customerOrg", "patientRegister", "report"]),
  },
  //创建组件后
  created() {
    this.dataCusOrgOCX = [];
  },

  //挂载组件完成
  mounted() {
    //获取体检单位列表树信息
    this.getCustomerOrgTree();
  },

  methods: {
    //获取体检单位列表树信息
    getCustomerOrgTree() {
      getapi("/api/app/customerorg/getbycodeall").then((res) => {
        //customerOrgTree = res.data;
        console.log("res.data", res.data);
        this.patientRegister.customerOrgTreeAll = res.data;
        //tcdate(this.patientRegister.customerOrgTreeAll)
      });
    },

    //获取体检单位父级ID api/app/customer-org/parent/[CustomerOrgld
    getCustomerOrgParentId(customerOrgld) {
      if (customerOrgld == this.dict.personOrgId) {
        this.patientRegister.query.CustomerOrgParentId = this.dict.personOrgId;
        return;
      }
      getapi(`/api/app/customer-org/parent/${customerOrgld}`).then((res) => {
        console.log("res.data", res.data);
        if (res.code == 1) {
          this.patientRegister.query.CustomerOrgParentId = res.data;
        }
      });
    },

    //点击树节点
    treeclick(data) {
      this.patientRegister.query.customerOrgId = data.id;
      this.getCustomerOrgParentId(data.id);
      this.patientRegister.query.times++; //用于触发查询条件
    },

    //树控件--伪双击事件
    handleNode(data, node, prop) {
      // console.log(data, node, prop);
      if (!this.preNodeId) {
        this.preNodeId = data.id;
      } else {
        this.curNodeId = data.id;
      }
      //双击事件
      if (this.preNodeId == this.curNodeId) { //第一次点击的节点和第二次点击的节点id相同
        this.preNodeId = null;
        this.curNodeId = null;
        this.treeDbClick(data);
        return;
      }

      this.nodeTimer = setTimeout(() => { //300ms内没有第二次点击就把第一次点击的清空
        this.preNodeId = null;
      }, 300)
    },

    //双击树节点 后续处理
    async treeDbClick(node) {
      //console.log('this.patientRegister.customerOrgTreeAll',this.patientRegister.customerOrgTreeAll);
      if (!this.useCusOrg) {
        this.$message.info("请先勾选单位作为查询条件");
        return;
      }      

      //待添加的记录
      let ldate = new Date();
      let record = {
        id: parseInt(Math.random() * 100000000),
        customerOrgId: node.id,
        customerOrgName:node.displayName,
        customerOrgRegister: {},     //已选的体检次数
        customerOrgRegisterList: [], //当前单位的体检次数信息
        dateType: 'creationTime',  // 登记日期：creationTime；体检日期：medicalStartDate；总检日期：summaryDate
        startDate: ldate,
        endDate: ldate,
        customerOrgGroupIds: [],  //已选的体检分组
        customerOrgGroupList: [],  //可选的分组
      }

      if (node.id != this.dict.personOrgId) {
        try {
          let res = await getapi(`/api/app/customer-org/parent/${node.id}`);
          let res1 = await getapi(`/api/app/customerorgregister/getlistincustomerorgid?CustomerOrgId=${res.data}`);
          record.customerOrgRegisterList = res1.data;
          if (res1.data && res1.data.length > 0) {
            record.customerOrgRegister = res1.data[res1.data.length - 1];
            record.startDate = res1.data[res1.data.length - 1].beginTime;
            record.endDate = res1.data[res1.data.length - 1].isComplete == 'N' ? ldate : res1.data[res1.data.length - 1].endTime;
          }
        } catch (error) {
          console.log(`get: /api/app/customer-org/parent/${node.id}  /api/app/customerorgregister/getlistincustomerorgid?CustomerOrgId=${node.id}`, error)
        }
      }

      let checkMsg = this.checkQuery(record, this.dataCusOrgOCX, 0, -1);

      if (checkMsg) {
        this.$message.warning(checkMsg);
        return;
      }

      this.dataCusOrgOCX.push(record);

    },

    //查询条件合法性检测
    checkQuery(record, dataCusOrgOCX, startRow, currRow) {
      //currRow 为 - 1 时，record 表示 待添加记录 ,否则为 dataCusOrgOCX 列表数据 合法性检测
      if(!record.customerOrgId) return '';
      if(!dataCusOrgOCX || dataCusOrgOCX.length < 1) return '';

      let checkMsg = '';
      let parentIds = getTreePids(this.patientRegister.customerOrgTreeAll, 'treeChildren', 'parentId', 'id', record.customerOrgId);
      let childIds = getTreeAllChildIdsById(this.patientRegister.customerOrgTreeAll, 'treeChildren', 'id', record.customerOrgId);

      for (let i = startRow; i < dataCusOrgOCX.length; i++) {
        if (dataCusOrgOCX[i].customerOrgId == record.customerOrgId && dataCusOrgOCX[i].customerOrgRegister.id == record.customerOrgRegister.id) {
          if (currRow < 0) {
            checkMsg = "已经添加了该单位，不可再添加";
          } else {
            checkMsg = `第 ${Number(currRow) + 1} 行与第 ${Number(i) + 1} 行，单位与体检次数相同，数据校验失败！`;
          }
          break;
        }
        if (parentIds.indexOf(dataCusOrgOCX[i].customerOrgId) > - 1 && dataCusOrgOCX[i].customerOrgRegister.id == record.customerOrgRegister.id) {
          if (currRow < 0) {
            checkMsg = "已经添加了该单位的上级单位，不可再添加该单位";
          } else {
            checkMsg = `第 ${Number(currRow) + 1} 行与第 ${Number(i) + 1} 行，体检次数相同单位存在上下级关系，数据校验失败！`;
          }
          break;
        }
        if (childIds.indexOf(dataCusOrgOCX[i].customerOrgId) > - 1 && dataCusOrgOCX[i].customerOrgRegister.id == record.customerOrgRegister.id) {
          if (currRow < 0) {
            checkMsg = "已经添加了该单位的下级单位，不可再添加该单位";
          } else {
            checkMsg = `第 ${Number(currRow) + 1} 行与第 ${Number(i) + 1} 行，体检次数相同单位存在上下级关系，数据校验失败！`;
          }
          break;
        }
      }


      return checkMsg;

    },

    //修改体检次数，更改起止日期
    changeMedicalTimes(index) {

      let v = this.dataCusOrgOCX[index].customerOrgRegister;

      this.dataCusOrgOCX[index].startDate = v.beginTime;
      this.dataCusOrgOCX[index].endDate = v.isComplete == 'N' ? new Date() : v.endTime;

      //清除选的分组
      this.dataCusOrgOCX[index].customerOrgGroupIds = [];

    },

    //选分组
    getCustGroup(index, groupId) {
      ///api/app/customerorggroup/getlistinfilter?CustomerOrgRegisterId=3fa85f64-5717-4562-b3fc-2c963f66afa6
      getapi(`/api/app/customerorggroup/getlistinfilter?CustomerOrgRegisterId=${groupId}`).then(res => {
        if (res.code != - 1) {
          this.dataCusOrgOCX[index].customerOrgGroupList = res.data.items;
        }
      })
    },

    //选择日期方式
    changeDateType(v) {
      this.dataCusOrgOCX.forEach(e => {
        e.dateType = v;
        return e;
      })
    },

    changeUseOrg(v) {
      let ldate = new Date();
      this.dataCusOrgOCX = [];
      if (!v) {
        this.dataCusOrgOCX.push({
          id: parseInt(Math.random() * 100000000),
          customerOrgId: '',
          customerOrgName: '',
          customerOrgRegister: {},     //已选的体检次数
          customerOrgRegisterList: [], //当前单位的体检次数信息
          dateType: 'creationTime',  // 登记日期：creationTime；体检日期：medicalStartDate；总检日期：summaryDate
          startDate: ldate,
          endDate: ldate,
          customerOrgGroupIds: [],  //已选的体检分组
          customerOrgGroupList: [],  //可选的分组
        })
      }
    },

    //双击删除该行查询条件
    rowDblclick(row) {
      let lfind = arrayExistObj(this.dataCusOrgOCX, 'id', row.id);
      if (lfind > -1) this.dataCusOrgOCX.splice(lfind, 1);
    },

    //选择单位
    changeCustomerOrgId(v) {
      console.log(v)
      if (!v) {
        this.patientRegister.query.customerOrgRegister = null;
        return;
      }

      let customerOrgId = v[0];
      if (customerOrgId == this.dict.personOrgId) {
        this.patientRegister.query.customerOrgRegister = null;
        return;
      }
      getapi(
        `/api/app/customerorgregister/getlistincustomerorgid?CustomerOrgId=${customerOrgId}`
      ).then((res) => {
        //console.log('res.data',res.data)
        if (res.code != -1) {
          this.customerOrg.customerOrgRegisterList = res.data;
          if (res.data.length > 0) {
            this.patientRegister.query.customerOrgRegister = res.data[res.data.length - 1];
            this.patientRegister.query.dateRange = [
              res.data[res.data.length - 1].beginTime,
              res.data[res.data.length - 1].isComplete == 'N' ? new Date() : res.data[res.data.length - 1].endTime
            ]
          }
        }
      });
    },

    btnOk(){
      let checkMsg = '',cusOrgOCX='';
      for(let i=0;i<this.dataCusOrgOCX.length;i++){
        checkMsg = this.checkQuery(this.dataCusOrgOCX[i],this.dataCusOrgOCX,i+1,i);
        if(checkMsg) break;
      }
      if(checkMsg) {
        this.$message.warning(checkMsg);
        return;
      }

      if(this.dataCusOrgOCX && this.dataCusOrgOCX.length > 0){
        cusOrgOCX = this.dataCusOrgOCX[0].customerOrgName || '';
        switch (this.dataCusOrgOCX[0].dateType) {
          case 'medicalStartDate':
            cusOrgOCX += "(体检"
            break;
          case 'summaryDate':
            cusOrgOCX += "(总检"
            break;
          default:
            cusOrgOCX += "(登记"
            break;
        }

        cusOrgOCX += moment(this.dataCusOrgOCX[0].startDate).format('yyyy-MM-DD') + '~' + moment(this.dataCusOrgOCX[0].endDate).format('yyyy-MM-DD') + ')';

      }      

      this.report.dataCusOrgOCX = this.dataCusOrgOCX;
      this.patientRegister.query.cusOrgOCX = cusOrgOCX

      this.report.dialogCusOrgOCX = false;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../assets/css/global_dialog.css";
@import "../../assets/css/global_table.css";
@import "../../assets/css/global_input.css";
@import "../../assets/css/global.css";

</style>
