<template>
  <div style="display: flex;">
    <div style="width: 150px;height:500px;margin-top: -30px;overflow: scroll;border: 1px solid;">
      <el-tree :data="patientRegister.customerOrgTreeAll" :props="customerOrg.treeprops" @node-click="handleNode" />
    </div>
    <div style="display: block;width:650px;margin-top: -30px; margin-left: 5px;">
      <el-table :data="dataCusOrgOCX" border height="450" highlight-current-row @row-click="rowick" size="small"
        @selection-change="handleSelectionChange" @cell-contextmenu="onCellRightClick">
        <el-table-column prop="customerOrgId" label="体检单位" width="130">
          <template slot-scope="scope">            
            <el-cascader v-model="scope.row.customerOrgId" :options="patientRegister.customerOrgTreeAll"
              :props="{ checkStrictly: true, expandTrigger: 'hover', ...customerOrg.treeprops, }" placeholder="请选择单位"
              :show-all-levels="false" disabled clearable size="small" @change="changeCustomerOrgId" style="width:125px;">
            </el-cascader>
          </template>
        </el-table-column>
        <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="scope.row.customerOrgId == dict.personOrgId"
              @change="changeMedicalTimes(scope.row.customerOrgId)" 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="80" 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="80" 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="215">
          <template slot-scope="scope">
            <el-select v-model="scope.row.customerOrgGroupIds" multiple collapse-tags filterable clearable style="width:210px;"
              placeholder="请选择分组" size="small" @focus="getCustGroup(scope.$index,scope.row.customerOrgRegister.id)">
              <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>
      <div style="display: flex;margin-top: 8px;margin-left: 15px;">
        <div style="display: block;">
          <div>
            <span>日期方式：</span>
            <el-radio-group v-model="dateType">
              <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" />
          </div>
        </div>
        <div style="margin-left: 50px;margin-top: 5px;">
          <el-button type="primary" @click="readIdCard">确定</el-button>
          <el-button type="danger" @click="report.dialogCusOrgOCX = false">关闭</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { tcdate } from "../../utlis/proFunc";
import { getTreePids, getTreeAllChildIdsById } from "../../utlis/tree";
export default {
  components: {},
  data() {
    return {
      preNodeId: '',  //上一次点击树节点
      curNodeId: '',  //本次点击树节点 
      parentIds: [],   //上级Id 数组
      childIds: [],    //下级Id 数组  
      dateType: 'creationTime',
      useCusOrg: true,   //是否使用单位
      //体检单位，体检次数，日期类型，起止日期，分组
      dataCusOrgOCX: [{
        customerOrgId: '',
        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 = this.report.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) {
      this.parentIds = getTreePids(this.patientRegister.customerOrgTreeAll, 'children', 'parentId', 'id', node.id);
      this.childIds = getTreeAllChildIdsById(this.patientRegister.customerOrgTreeAll, 'children', 'id', node.id);

      //待添加的记录
      let ldate = new Date();
      let record = {
        customerOrgId: '',
        customerOrgRegister: {},     //已选的体检次数
        customerOrgRegisterList: [], //当前单位的体检次数信息
        dateType: 'creationTime',  // 登记日期：creationTime；体检日期：medicalStartDate；总检日期：summaryDate
        startDate: ldate,
        endDate: ldate,
        customerOrgGroupIds: [],  //已选的体检分组
        customerOrgGroupList: [],  //可选的分组
      }
      record.customerOrgId = node.id;
      if(node.id != this.dict.personOrgId){ 
        try {
          //let res = 
          let res1 = await getapi(`/api/app/customerorgregister/getlistincustomerorgid?CustomerOrgId=${cusOrgId}`);
          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/customerorgregister/getlistincustomerorgid?CustomerOrgId=${cusOrgId}`,error)
        }
      }

      let  insableMsg = '';      
      this.dataCusOrgOCX.forEach(e =>{
        if(this.parentIds.indexOf(e.customerOrgId) > - 1 && e.customerOrgRegister.id == record.customerOrgRegister.id){
          insableMsg = "已经添加了上级节点，不可再添加此节点";
        }
        if(this.childIds.indexOf(e.customerOrgId) > - 1 && e.customerOrgRegister.id == record.customerOrgRegister.id){
          insableMsg = "已经添加了下级节点，不可再添加此节点";
        }
      });

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

      this.dataCusOrgOCX.push(record);

    },

    //选分组
    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;
        }
      })
    },

    //选择单位
    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
            ]
          }
        }
      });
    },

  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-input__inner {
  /*text-align: center;*/
  padding-left: 1px;
  padding-right: 1px;
}

::v-deep .el-table th.el-table__cell {
  /*text-align: center;*/
  padding-left: 1px;
  padding-right: 1px;
}

::v-deep .el-table td.el-table__cell {
  padding-left: 1px;
  padding-right: 1px;
}

::v-deep .el-table .cell {
  padding-left: 1px;
  padding-right: 1px;
}

::v-deep .el-icon-date:before {
    content: ""
}
</style>
