<template>
  <div>
    <div>
      <el-table :data="bigTexts" style="width: 100%;" highlight-current-row @row-click="rowClick" height="260">
        <el-table-column type="index" label="序号" width="40" align="center" />
        <el-table-column prop="bigtextResultTypeName" label="词条类别" min-width="80" align="center" />
        <el-table-column prop="bigtextResultTemplateName" label="词条模版" min-width="150" align="center" />
        <el-table-column prop="bigtextResultConclusion" label="检查结论" min-width="150" align="center" />
        <el-table-column prop="bigtextResultDescription" label="检查描述" min-width="400" />
      </el-table>
    </div>
    <div style="display: flex;margin-top: 5px;">
      <div style="width: 49%;">
        <!-- 多个检查明细 -->
        <div style="display: flex; justify-content: space-between;height: 20px;">
          <div><span>检查结果：</span></div>
          <div>
            <el-tooltip :content="`给 ${doctorCheck.checkItemList[refParams.index].itemName} 项目，赋默认结果`" placement="top">
              <i class="el-icon-edit" @click="btnDefResult(refParams.index)"
                style="font-size: 18px;color: blue;cursor: pointer;margin-right: 10px;"></i>
            </el-tooltip>
            <el-tooltip :content="`清除 ${doctorCheck.checkItemList[refParams.index].itemName} 项目的检查结果`" placement="top">
              <i class="el-icon-delete" @click="btnClear(refParams.index)"
                style="font-size: 18px; color: red;cursor: pointer;margin-right: 10px;"></i>
            </el-tooltip>
          </div>
        </div>
        <div>
          <el-input style="width: 100%" type="textarea" v-model="doctorCheck.checkItemList[refParams.index].result"
            placeholder="请输入检查结果" :autosize="{ minRows: 9, maxRows: 9 }" />
        </div>
      </div>
      <div style="margin-left: 8px; width: 50%;">
        <div style="display: flex; justify-content: space-between;height: 20px;">
          <div><span>检查结论：</span></div>
          <div>
          </div>
        </div>

        <div>
          <el-table row-key="id" :data="doctorCheck.checkSummaryList" size="samll" height="186"
            width="100%" border>
            <el-table-column width="30" align="center">
              <template slot-scope="scope">
                <el-tag class="moveSummary" style="height:25px;padding:0 2px;cursor: move;background-color: #EEEEEE;">
                  <div style="width: 16px;">{{ scope.$index + 1 }}</div>
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="summary" label="小结">
              <template slot="header">
                <div style="display: flex;justify-content:space-between;">
                  <div>小结</div>
                  <div></div>
                </div>
              </template>
              <template slot-scope="scope">
                <div style="display: flex;">
                  <el-input type="textarea" v-model="scope.row.summary" :autosize="{ minRows: 1, maxRows: 100 }"
                    placeholder="请输入小结">
                  </el-input>
                  <el-button type="danger" style="min-width:23px;padding:2px;" icon="el-icon-delete"
                    @click="delSum(scope.$index)" size="small"></el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!--可选结果-->
    <div style="display: flex; justify-content: space-between; margin-top: 5px">
      <div style="width: 730px;">
        <el-table row-key="id" :data="resultOptRows" size="samll" width="100%" border>
          <el-table-column v-for="col in resultOpts" :key="col.resultTemplate" width="120" align="left">
            <template slot="header">{{ col.resultTemplate }}</template>
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row[col.resultTemplate]" @input="radioGroupInput">
                <div v-for="opt in col.opts" :key="opt" style="margin-left: 10px;">
                  <el-radio :label="opt" style="margin: 5px 0;">{{ opt }}</el-radio>
                </div>
              </el-radio-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style=" margin-top: 5px">
        <!--
          <el-button type="primary" @click="btnTest" class="commonbutton">测试</el-button>
            -->
        <el-button type="primary" @click="btnOk" class="commonbutton">确定</el-button>
      </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";


export default {
  components: {},
  props: ["refParams", "refFuncOther"],
  data() {
    return {
      bigTexts: [{
        bigtextResultTypeName: "",
        bigtextResultTemplateName: "",
        bigtextResultConclusion: "",
        bigtextResultDescription: ""
      }], // 大文本词条
      result: "", //隐藏在后台处理数据用

      resultOpts: [
        { resultTemplate: "[A|B|C|D]", opts: ['A', 'B', 'C', 'D'], chooseOpt: 'A' }
      ],  // [|] 结果带选项
      resultOptRows: [

      ],
    };
  },
  //<el-tree :data="$store.state.customerOrg.ref_tree" :props="$store.state.customerOrg.treeprops" @node-click="treeclick"></el-tree>
  computed: {
    ...mapState(["window", "dialogWin", "doctorCheck"]),
  },
  //创建组件后
  created() { },

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

  methods: {
    // 初始化数据
    init() {
      this.result = this.doctorCheck.checkItemList[this.refParams.index].result
      this.resultOpts = []
      this.madeResultOpts()

      let itemId = this.doctorCheck.checkItemList[this.refParams.index].itemId

      //"itemId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"

      postapi('/api/app/BigtextResultTemplate/GetBigtextResultTemplateWithDetail', { itemId })
        .then(res => {
          if (res.code > -1) {
            this.bigTexts = res.data
          }
        })
    },

    // 分析可选模版 [A|B|C|D]
    madeResultOpts() {
      this.resultOptRows = []
      if (!this.result) return
      let opts1 = this.result.split(']')
      opts1.forEach(e => {
        let opts2 = e.split('[')
        if (opts2.length == 2) {
          if (opts2[1].includes('|')) {
            let resultTemplate = `[${opts2[1]}]`
            let lfind = arrayExistObj(this.resultOpts, 'resultTemplate', resultTemplate)
            if (lfind == -1) {
              let opts = opts2[1].split('|')
              let chooseOpt = ''
              this.resultOpts.push({ resultTemplate, opts, chooseOpt })
            }
          }
        }
      });
      let resultOptRow = { id: 1 }
      if (this.resultOpts.length > 0) {
        this.resultOpts.forEach(e => {
          resultOptRow[e.resultTemplate] = e.chooseOpt
        });
      }
      this.resultOptRows.push(resultOptRow)
    },

    // 
    radioGroupInput(v){
      // console.log('radioGroupInput',this.resultOptRows,this.refParams.index)
      let result = this.result
      this.resultOpts.forEach(e => {
        if(this.resultOptRows[0][e.resultTemplate]) result = result.replace(e.resultTemplate,this.resultOptRows[0][e.resultTemplate])        
      });
      this.doctorCheck.checkItemList[this.refParams.index].result = result
    },

    // 选择结果模版 (true 则添加，false则取消)  老板说，只有选，没有取消选择
    rowClick(row) {
      // bigtextResultTypeName: "",
      // bigtextResultTemplateName: "",
      // bigtextResultConclusion: "",
      // bigtextResultDescription: ""
      let chooseOpra = true
      let conclusions = []
      let result = this.doctorCheck.checkItemList[this.refParams.index].result
      if (result) {
        if (result == this.doctorCheck.checkItemList[this.refParams.index].defaultResult) {
          chooseOpra = true
          result = row.bigtextResultDescription
        } else {
          // 
          if (result.includes(row.bigtextResultDescription)) {
            return  // 老板说，只有选，没有取消选择
            // chooseOpra = false
            // result = result.replaceAll(`；${row.bigtextResultDescription}`, '').replaceAll(`${row.bigtextResultDescription}；`, '').replaceAll(`${row.bigtextResultDescription}`, '')
            // if (!result) result = this.doctorCheck.checkItemList[this.refParams.index].defaultResult
          } else {
            chooseOpra = true
            result += "；" + row.bigtextResultDescription
          }
        }
      } else {
        chooseOpra = true
        result = row.bigtextResultDescription
      }
      this.doctorCheck.checkItemList[this.refParams.index].result = result
      this.result = result
      this.madeResultOpts()

      if (row.bigtextResultConclusion) conclusions = row.bigtextResultConclusion.split("；")
      if (conclusions.length > 0) {
        let lfind = -1
        conclusions.forEach(e => {
          if (chooseOpra) {
            lfind = -1
            this.doctorCheck.checkSummaryList.forEach(c => {
              if (c.summary == e) lfind = 1
            });
            // 没找到，则添加结论
            if (lfind == -1) {
              this.doctorCheck.checkSummaryList.push({
                id: Math.random(),
                registerCheckId: this.doctorCheck.RegisterCheckEdit.id,
                summary: e,
                summaryFlag: 'N',
              })
            }
          } else {
            if (this.doctorCheck.checkSummaryList.length > 0) {
              for (let i = this.doctorCheck.checkSummaryList.length - 1; i > -1; i--) {
                if (e == this.doctorCheck.checkSummaryList[i].summary) this.doctorCheck.checkSummaryList.splice(i, 1)
              }
            }
          }
        });
      }
    },

    //删除小结
    delSum(index) {
      this.$confirm("此操作将删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }).then(() => {
        this.doctorCheck.checkSummaryList.splice(index, 1);
      }).catch(err => {
        if (err == "cancel") {
          // this.$message.info("已取消删除");
          console.log('已取消删除')
        }
      });
    },

    //勾选节点
    handleCheckChange(data, checked, indeterminate) {
      // console.log('data, checked, indeterminate,this.menuInfoSet',data, checked, indeterminate,this.menuInfoSet);

      this.description = [];
      this.conclusion = [];
      postapi("/api/app/BigtextResultTemplate/GetBigtextResultTemplateDetail", {
        bigtextResultTemplateIds: [data.id],
      }).then((res) => {
        if (res.code > -1) {
          this.description = res.data.descriptionDetail;
          this.conclusion = res.data.conclusionDetail;
          let opraType = false;
          if (checked) {
            // 勾选
            opraType = true;
          } else if (!indeterminate) {
            // 取消勾选
            opraType = false;
          }
          this.chooseDescription(opraType);
          this.chooseConclusion(opraType);
        }
      });
    },




    // 清除结果
    btnClear(seq) {
      this.doctorCheck.checkItemList[seq].result = "";
    },

    // 默认结果
    btnDefResult(seq) {
      this.doctorCheck.checkItemList[seq].result =
        this.doctorCheck.checkItemList[seq].defaultResult;
    },


    // 确定
    btnOk() {
      this.refFuncOther(this.refParams.row, this.refParams.index, {
        result: this.result,
        summary: this.summary,
      });
      this.dialogWin.PacsTemplate = false;
    },
  },

  watch: {
    "refParams.refresh"(newVal, oldVal) {
      if (newVal && newVal != oldVal) this.init();
    }
  },
};
</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>
