<template>
  <div style="display: flex;">
    <div :style="`width: 258px;height:${mainHeight}px;border: 1px solid #EEE;`">
      <div style="margin:2px 2px 2px 2px;">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText" size="small" />
      </div>
      <div>
        <el-tree :style="`overflow: scroll;width: 200px;height:${mainHeight - 40}px;`" :data="pacsTemplateTree"
          :props="treeprops" @node-click="handleNode" :filter-node-method="filterNode" :expand-on-click-node="false"
          highlight-current ref="ref_tree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <div>
              <span class="treeicons">
                <img style="width:20px;height:20px;vertical-align: sub;" src="@/assets/images/order.png"
                  v-if="!data.parentId" />
              </span>
              <span :class="!data.parentId ? 'maxtitle' : 'mintitle'">{{ node.label }}
              </span>
            </div>
          </span>
        </el-tree>
      </div>
    </div>
    <div :style="`display: block;width:${window.pageWidth - 200 - 30}px; margin-left: 5px;`">
      <div style="display: flex;">
        <div :style="`width: ${window.pageWidth - 200 - 30 - 250}px;`">
          <el-table :data="description" border :height="tableHeight" highlight-current-row
            @selection-change="selectionChangeDes" size="small" ref="ref_description">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column prop="description" label="描述" min-width="400" />
            <el-table-column prop="conclusion" label="结论" min-width="150" align="center" />
          </el-table>
        </div>
        <div style="width: 240px;margin-left: 5px;">
          <el-table :data="conclusionAll" border :height="tableHeight" highlight-current-row
            @selection-change="selectionChangeCon" size="small" ref="ref_conclusion">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column prop="conclusion" label="结论" min-width="150" />
          </el-table>
        </div>
      </div>
      <div style="margin-top: 5px;">
        <span>检查结果：</span>
        <el-input style="width: 100%;" type="textarea" v-model="result" placeholder="请输入描述"
          :autosize="{ minRows: 6, maxRows: 6 }" />
      </div>
      <div style="margin-top: 5px;">
        <span>检查结论：</span>
        <div style="display: flex;justify-content: space-between;">
          <el-input style="width: 100%;" type="textarea" v-model="summary" placeholder="请输入结论"
            :autosize="{ minRows: 4, maxRows: 4 }" />
        </div>
      </div>
      <div style="display: flex;justify-content: space-between;margin-top: 10px;">
        <div></div>
        <div>
          <el-button type="primary" @click="btnTest" class="commonbutton">测试</el-button>
          <el-button type="primary" @click="btnClear" class="commonbutton">清除</el-button>
          <el-button type="primary" @click="btnDefault" class="commonbutton">默认结果</el-button>
          <el-button type="primary" @click="btnOk" class="commonbutton">确定</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 { hadoopGet, hadoopPost, hadoopPut, hadoopDel } from "../../api/hadoopApi"
import { arrayReduce, arrayExistObj, deepCopy, reMadeOrgTree } from "../../utlis/proFunc";
import { getTreePids, getTreeAllChildIdsById, madeTree } from "../../utlis/tree";

export default {
  components: {},
  props: ["useCustomerOrg", "initDateType", "isUnit"],
  data() {
    return {
      filterText: '',
      description: [],  // 描述      
      conclusion: [],  // 结论
      descriptionChoosedPre: [], // 前次选中
      descriptionChoosed: [],  // 所有选中的描述的集合，切换部位时可用于描述初始化选择
      conclusionChoosed: [],  // 选中的结论
      conclusionAll: [],  // 所有选中的描述，对应的结论
      result: '', // 检查结果
      summary: '', // 小结
      pacsTemplateTree: [], //类别 + 模板树
      treeprops: {
        label: "displayName",  // label/displayName
        value: "id",
        id: "id",
        children: "children",
      }, //树形组件的数据结构 
      newQuery: 0, // 0 表示新查询，新查询不执行 selectionChangeDes 的取消查询动作
    };
  },
  //<el-tree :data="$store.state.customerOrg.ref_tree" :props="$store.state.customerOrg.treeprops" @node-click="treeclick"></el-tree>
  computed: {
    ...mapState(["dict", "window", "customerOrg", "patientRegister", "report", "diagnosis", "project"]),

    mainHeight() {
      return this.window.pageHeight - 78;
    },

    tableHeight() {
      return this.mainHeight - 120 - 80 - 80;
    },
  },
  //创建组件后
  created() {

  },


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

  methods: {

    //树过滤
    filterNode(value, data) {
      //console.log(value,data)
      if (!value) return true;
      return data['displayName'].indexOf(value) > -1;
    },

    //获取pacs结果模板
    getPacsTemplateTree() {
      let resultType = [], resultTemplate = [], treeData = []

      postapi('/api/app/BigtextResultType/GetList')
        .then(res => {
          if (res.code > -1) {
            resultType = res.data
            return postapi('/api/app/BigtextResultTemplate/GetList', {})
          }
        })
        .then(res => {
          if (res && res.code > -1) {
            res.data.forEach(e => {
              resultTemplate.push(Object.assign({}, e, { parentId: e.bigtextResultTypeId }))
            });
            treeData = resultType.concat(resultTemplate)
            // console.log('treeData',treeData,resultType,)
            this.pacsTemplateTree = madeTree(treeData, "children", "parentId", "id", null)
          }
        })
    },

    //点击树节点
    handleNode(data, node, prop) {
      let ids = getTreeAllChildIdsById(this.pacsTemplateTree, "children", "id", data.id)
      ids.unshift(data.id) // 加入自身节点

      hadoopPost('pacsApi','/api/app/BigtextResultTemplate/GetBigtextResultTemplateDetail', { bigtextResultTemplateIds: ids })
        .then(res => {
          if (res.code > -1) {
            this.newQuery = 0
            this.description = res.data.descriptionDetail
            this.conclusion = res.data.conclusionDetail
            let lfind = -1
            this.description.forEach((e, i) => {
              let conclusion = this.conclusion.filter(c => {
                return c.bigtextResultTemplateId == e.bigtextResultTemplateId
              })
              e["conclusion"] = ""
              e["conclusionList"] = []
              conclusion.forEach(c => {
                e["conclusionList"].push(c)
              });
              if (conclusion.length == 1) e["conclusion"] = conclusion[0].conclusion

              // 初始选中状态              
              lfind = arrayExistObj(this.descriptionChoosed, "description", e.description)
              if (lfind > -1) {
                // console.log('this.descriptionChoosed refresh', deepCopy(this.descriptionChoosed))
                this.$nextTick(() => {
                  this.$refs['ref_description'].toggleRowSelection(this.description[i],true)
                })                
              }
            });

          }
        })

    },


    // 选择描述
    selectionChangeDes(v) {
      this.newQuery++
      let lfind = 0
      v.forEach(e => {
        lfind = arrayExistObj(this.descriptionChoosed, "description", e.description)
        if (lfind == -1) {
          this.descriptionChoosed.push(e)
        }

        e.conclusionList.forEach(c => {
          lfind = arrayExistObj(this.conclusionAll, "conclusion", c.conclusion)
          if (lfind == -1) this.conclusionAll.push(c)
        });
        // 单个结论时，直接选中结论，多个则将结论添加至待选结论
        if (e.conclusion) {
          lfind = arrayExistObj(this.conclusionAll, "conclusion", e.conclusion)
          // console.log(lfind, e)
          if (lfind > -1) {
            this.$refs['ref_conclusion'].toggleRowSelection(this.conclusionAll[lfind], true)
          }
        }

        if (this.result) {
          if (!this.result.includes(e.description)) this.result += '；' + e.description
        } else {
          this.result = e.description
        }
      });      

      // 这一次没选中的在上一次的选中当中，说明取消选择
      if (this.newQuery > 1) {
        let unChooseed = arrayReduce(deepCopy(this.description), v, "description=description")
        // console.log('this.descriptionChoosedPre,unChooseed', deepCopy(this.descriptionChoosedPre), unChooseed)
        unChooseed.forEach(e => {
          lfind = arrayExistObj(this.descriptionChoosedPre, "description", e.description)
          if (lfind > -1) {
            lfind = arrayExistObj(this.descriptionChoosed, "description", e.description)
            if (lfind > -1) this.descriptionChoosed.splice(lfind, 1)

            if (this.result.includes(e.description)) this.result = this.result.replaceAll(e.description + "；", "").replaceAll(e.description, "")
            if (e.conclusion) {
              lfind = arrayExistObj(this.conclusionAll, "conclusion", e.conclusion)
              if (lfind > -1) this.$refs['ref_conclusion'].toggleRowSelection(this.conclusionAll[lfind], false)
            }
          }
        });
      }
      this.descriptionChoosedPre = deepCopy(v)
      if(this.result){
        if(this.result.substring(this.result.length - 1,this.result.length) == "；") this.result = this.result.substring(0,this.result.length - 1)        
      }
    },

    // 选择结论(取消选择)
    selectionChangeCon(v) {
      let summarys = []
      v.forEach(e => {
        if (this.summary) {
          summarys = this.summary.split("；")
          if (summarys.indexOf(e.conclusion) == -1) this.summary += '；' + e.conclusion
        } else {
          this.summary = e.conclusion
        }
      });
      // if(this.summary && this.summary.substring())

      // 取消选择时
      let lfind = -1
      let unChooseed = arrayReduce(deepCopy(this.conclusionAll), v, "conclusion=conclusion")
      unChooseed.forEach(e => {
        if (this.summary) {
          summarys = this.summary.split("；")
          lfind = summarys.indexOf(e.conclusion)
          if (lfind > -1) summarys.splice(lfind, 1)
          this.summary = ''
          summarys.forEach((c, i) => {
            if (i == 0) {
              this.summary = c
            } else {
              this.summary += "；" + c
            }
          });
        }
      });
    },

    btnTest() {
      console.log('this.descriptionChoosed', this.descriptionChoosed)
      console.log('this.conclusionChoosed', this.conclusionChoosed)
    },

    // 清除所选描述与结论
    btnClear() {
      this.result = ''
      this.summary = ''
      this.descriptionChoosed = []
      this.$refs['ref_description'].clearSelection();

      this.conclusionChoosed = []
      this.conclusionAll = []
      this.$refs['ref_conclusion'].clearSelection();
    },

    // 默认结果
    btnDefault() {

    },

    // 确定
    btnOk() {
      this.dialogWin.PacsTemplate = false
    },
  },
  watch: {
    "filterText"(newVal, oldVal) {
      if (newVal != oldVal) this.$refs['ref_tree'].filter(newVal);
    }
  },
};
</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";
@import "../../assets/css/global_tree.css";

:deep .el-tree-node>.el-tree-node__children {
  overflow: visible;
}
</style>
