<template>
  <div class="box">
    <div>
      <div class="middlebox">
          <div class="contenttitle">
            基础资料 /
            <span class="contenttitleBold"
              >诊断建议设置</span
            >
          </div>
          <div class="seachinput">
            <el-select v-model="diagnosis" placeholder="快速查找" size="small" 
                    filterable   :filter-method="filterMethod" value-key="id"
                    clearable @clear="quickTableData = deepCopy(tableData)" 
                    @change="quickDiagnosis" default-first-option ref="elSelectKeyWords">
                    <!-- 
                    <el-option key='1' value="" label="1" />
                    <el-option key='2' value="{id:'2',displayName:'n2'}" label="2" />
                     -->
                    <!--  -->
                    <el-option v-for="item in quickTableData" :key="item.id" :value="item" :label="item.displayName" />
                    
                  </el-select>
          </div>
      </div>     
      <div style="display: flex;margin-top: 7px;">
        <!-- 类别树组件 -->
        <div :style="'width: 208px; height:' +(window.pageHeight < 600 ? 505 : window.pageHeight - 100) +'px;background-color: #fff; border-radius: 8px'">
          <ItemTypeTree :refreshItemTypeId="refreshItemTypeId" :itemTypeId="query.itemTypeId"/>
        </div>
        <!-- 诊断与建议 -->
        <div style="display: block;">          
          <!-- 诊断列表 -->
          <div style="margin-left:15px;display: flex;">
            <div :style="'width:' + (window.pageWidth - 200 - 110 - 50-14) + 'px;padding: 15px;background-color: #fff;border-radius: 8px;'">
              <div style="margin-left: 5px;display: flex; flex-wrap: wrap;">
                <div>
                  <!--
                  <el-checkbox v-model="query.itemTypeFlag">项目类别作为查询条件</el-checkbox>                  
                  <el-input placeholder="查询关键字" v-model="query.keyWords" size="small" clearable style="width: 200px" />
                  -->
                  
                </div>
              </div>
              <div>
                <el-table :data="tableData" id="elTableDiagnosis" row-key="id"
                  :height="window.pageHeight < 600 ? 190 : Math.floor((window.pageHeight - 240) / 2)"
                  highlight-current-row @row-click="rowClick" size="small"  ref="elTable">
                  <el-table-column type="index" label="序号" width="40" align="center"/>
                  <el-table-column
                    v-for="(item, index) in headerCols" 
                    :key="`col_${index}`"          
                    :min-width="dropCol[index].minWidth"
                    :align="dropCol[index].align"
                    :label="item.label"
                  >        
                    <template slot-scope="scope">            
                      <div v-if="dropCol[index].prop == 'sn'" >
                        {{ scope.$index + 1 }}
                      </div>
                      <div v-else-if ="dropCol[index].prop == 'isIll' 
                                    || dropCol[index].prop == 'isSummaryTemplate'" >
                        {{ scope.row[dropCol[index].prop] == 'Y' ? '是':'否' }}
                      </div>
                      <!--
                      <div v-else-if="dropCol[index].prop == 'itemTypeId'" >
                        <el-cascader :options="dict.itemTypeTree" v-model="scope.row[dropCol[index].prop]" 
                          :props="{ checkStrictly: true, expandTrigger: 'hover', ...customerOrg.treeprops, }" :show-all-levels="false"
                          disabled size="small">
                        </el-cascader>                        
                      </div>
                      -->
                      <div v-else-if="dropCol[index].prop == 'diagnosisLevelId'" >
                        {{ dddw(dict.diagnosisLevel, "id", scope.row[dropCol[index].prop], "displayName") }}
                      </div>
                      <div v-else-if="dropCol[index].prop == 'forSexId'" >
                        {{ dddw(dict.forSex, "id", scope.row[dropCol[index].prop], "displayName") }}
                      </div>
                      <div v-else-if ="dropCol[index].prop == 'lastModificationTime' 
                                    || dropCol[index].prop == 'creationTime'" >
                        {{ scope.row[dropCol[index].prop] ? moment(scope.row[dropCol[index].prop]).format('yyyy-MM-DD HH:mm:ss'):'' }}
                      </div>
                      <div v-else>
                        {{ scope.row[dropCol[index].prop] }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="排序" width="40" align="center">
                    <template>
                      <el-tag
                        class="move"
                        style="
                          cursor: move;
                          background-color: rgb(245, 245, 245);
                          border: none;
                        "
                        draggable="true"
                      >
                        <i
                          class="el-icon-d-caret"
                          style="
                            width: 1rem;
                            height: 1rem;
                            color: rgb(113, 113, 113);
                          "
                        ></i>
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <!--按钮-->
            <div style="margin-left: 10px;">
              <!---->
              <div>
                <el-button class="commonbutton" @click="btnQuery">刷新</el-button>
              </div>
              <div style="margin-top: 10px">
                <el-button type="primary" class="commonbutton" @click="btnAdd">新增</el-button>
              </div>
              <div style="margin-top: 10px">
                <el-button type="success" class="commonbutton" @click="btnEdit">编辑</el-button>
              </div>
              <div style="margin-top: 10px">
                <el-button type="danger" class="deleteButton" @click="btnDel">删除</el-button>
              </div>
              <div style="margin-top: 10px">
                <el-button type="danger" class="commonbutton" @click="btnSort">保存排序</el-button>
              </div>
            </div>
          </div>

          <!-- 诊断对应的建议列表 -->
          <div style="margin-top:15px;">
            <DiagnosisSug :formDiagnosis="form" :refreshSugs="refreshSugs" :refreshSuges="refreshSuges" :refreshSugess="refreshSugess"/>
          </div>
        </div>
      </div>
    </div>

    <!--新增/编辑-->
    <el-dialog
      :title="form.id ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      width="800px" @close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="名称" prop="displayName">
              <el-input v-model="form.displayName" size="small" @input="inputDisplayName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目类别" prop="itemTypeId">
              <el-cascader :options="dict.itemTypeTree" v-model="form.itemTypeId" 
                :props="{ checkStrictly: true, expandTrigger: 'hover', ...customerOrg.treeprops, }" popper-class="example"
                ref="itemTypeIds"
                @change="ischangsItemTypeId"
                size="small">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="疾病" prop="isIll">
              <el-radio v-model="form.isIll" label="Y">是</el-radio>
              <el-radio v-model="form.isIll" label="N">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="建议名称" prop="suggestionName">
              <el-input v-model="form.suggestionName" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总检模板" prop="isSummaryTemplate">
              <el-radio v-model="form.isSummaryTemplate" label="Y">是</el-radio>
              <el-radio v-model="form.isSummaryTemplate" label="N">否</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="适用性别" prop="forSexId">
              <el-select v-model="form.forSexId" placeholder="请选择" size="small">
                <el-option
                  v-for="item in dict.forSex"
                  :key="item.id"
                  :label="item.displayName"
                  :value="item.id"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="诊断级别" prop="diagnosisLevelId">
              <el-select v-model="form.diagnosisLevelId" placeholder="请选择" size="small">
                <el-option
                  v-for="item in dict.diagnosisLevel"
                  :key="item.id"
                  :label="item.displayName"
                  :value="item.id"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="启用" prop="isActive">
              <el-radio v-model="form.isActive" label="Y">是</el-radio>
              <el-radio v-model="form.isActive" label="N">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="difference">取 消</el-button>
        <el-button type="primary" @click="onSubmit('form')" class="commonbutton">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

import moment from "moment";
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import Sortable from "sortablejs";

import ItemTypeTree from "../../components/common/ItemTypeTree.vue";
import DiagnosisSug from "./diagnosisSug.vue";
import { deepCopy,dddw, arrayExistObj, objCopy } from '@/utlis/proFunc';



export default {
  components: {
    ItemTypeTree,
    DiagnosisSug,
  },
  data() {
    return {
      query:{
        triggerScroll:0,    //触发按类别定
        itemTypeFlag:true, //项目类别是否 作为查询条件 
        itemTypeId:'',
        keyWords:'',        
      },
      diagnosis: {}, //null, //{id:'',displayName:''}
      tableData:[], //诊断列表(显示)
      diagnosisAll:[], // 所有诊断列表
      quickTableData:[], //快速查找诊断
      formInit:{},
      form:{
        id:'',
        itemTypeId:'',
        isIll:'Y',
        displayName:'',
        suggestionName:'',
        forSexId:'A',
        isSummaryTemplate:'N',
        isActive:'Y',
        diagnosisLevelId:1,  //
        medicalInterpretations:[],
        healthGuidances:[],
        commonReasons:[]
      },
      dialogVisible:false,
      rules: {
        displayName: [{ required: true, message: "请输入诊断名称", trigger: "blur" }],
        itemTypeId: [{ required: true, message: "请输入项目类别", trigger: "blur" }],        
      },

      //动态列（预留）
      headerCols: [],

      //拖动列（预留）
      dropCol: [
        //{ label: "序号",prop: "sn",minWidth: 40,align:"center"},
        // { label: "项目类别",prop: "itemTypeId",minWidth: 120,align:"center"},
        { label: "诊断级别",prop: "diagnosisLevelId",minWidth: 60,align:"center"},
        { label: "诊断名称",prop: "displayName",minWidth: 100,align:"center"},
        { label: "建议名称",prop: "suggestionName",minWidth: 100,align:"center"},
        { label: "疾病",prop: "isIll",minWidth: 40,align:"center"},
        { label: "适用性别",prop: "forSexId",minWidth: 60,align:"center"},
        { label: "总检模板",prop: "isSummaryTemplate",minWidth: 60,align:"center"},
        { label: "创建者",prop: "creatorName",minWidth: 60,align:"center"},
        { label: "创建时间",prop: "creationTime",minWidth: 130,align:"center"},
        { label: "修改者",prop: "lastModifierName",minWidth: 60,align:"center"},
        { label: "修改时间",prop: "lastModificationTime",minWidth: 130,align:"center"},
      ],
    };
  },

  created() {
    this.init()
  },

  //挂载完成
  mounted() { 
    this.rowDrop('elTableDiagnosis') 
    // this.btnQuery()
  },

  computed: {
    ...mapState(["customerOrg", "window","dict"]),
  },

  methods: {
    moment,dddw,deepCopy,

    init(){
      this.formInit = Object.assign({},this.form)
      this.headerCols = deepCopy(this.dropCol)

      //适用性别（查询）
      getapi("/api/app/for-sex").then((res) => {
        if (res.code != -1) {
          this.dict.forSex = res.data;
        }
      });

      //诊断级别
      getapi("/api/app/diagnosis-level/in-filter").then((res) => {
        if (res.code != -1) {
          this.dict.diagnosisLevel = res.data;
        }
      });

      this.allDiagnosis()

    },

    //查询所有 诊断记录 
    allDiagnosis(){
      postapi('/api/app/diagnosis/getlistinsuggestion',{}).then(res =>{
        if(res.code != -1){
          this.diagnosisAll = res.data
          this.quickTableData = res.data
        }
      })
    },

    // 供树节点组件调用，更新当前所选的项目类别
    refreshItemTypeId(itemTypeId){
      this.query.itemTypeId = itemTypeId
      this.query.triggerScroll++
    },

    // 供明建议组件调用，更新所选建议
    refreshSugs(sugs){
      if(!this.form.id) return
      this.form.medicalInterpretations = deepCopy(sugs)
      let lfind = arrayExistObj(this.tableData,'id',this.form.id)
      if(lfind > -1) this.tableData[lfind] = Object.assign(this.tableData[lfind],this.form)
    },
    refreshSuges(sugs){
      if(!this.form.id) return
      this.form.healthGuidances = deepCopy(sugs)
      let lfind = arrayExistObj(this.tableData,'id',this.form.id)
      if(lfind > -1) this.tableData[lfind] = Object.assign(this.tableData[lfind],this.form)
    },
    refreshSugess(sugs){
      if(!this.form.id) return
      this.form.commonReasons = deepCopy(sugs)
      let lfind = arrayExistObj(this.tableData,'id',this.form.id)
      if(lfind > -1) this.tableData[lfind] = Object.assign(this.tableData[lfind],this.form)
    },

    async btnQuery(){
      let body = {}
      if(this.query.itemTypeFlag && this.query.itemTypeId){
        body.itemTypeId = this.query.itemTypeId
      }else{
        return
      }
      // if(this.query.keyWords) body.keyWords = this.query.keyWords  

      postapi('/api/app/diagnosis/getlistinsuggestion',body).then(res =>{
        if(res.code != -1){
          this.tableData = res.data
          this.form = Object.assign({},this.formInit)
        }
      })      
    },

    //快速查找诊断时，调整可按拼间简码及简称查找
    filterMethod(keyWords) {
      //console.log('filterMethod',this.dict.asbItemQuick)  
      if (keyWords) {
        this.quickTableData = [];
        this.diagnosisAll.forEach(item => {
          if (item.displayName.indexOf(keyWords) > - 1
            || item.simpleCode.indexOf(keyWords.toUpperCase()) > - 1
            || item.suggestionName.indexOf(keyWords) > - 1) {
            this.quickTableData.push(item);
          }
        });
      } else {
        this.quickTableData = deepCopy(this.diagnosisAll);
      }
    },

    //快速查找诊断
    quickDiagnosis(v) {
      //远程查询时，设置了 value-key 也不管用，只能取到value console.log('quickDiagnosis',v)
      let lfind = -1
      if(!v.itemTypeId) return

      this.query.itemTypeId = v.itemTypeId
      let body = {
        itemTypeId:v.itemTypeId
      }  

      postapi('/api/app/diagnosis/getlistinsuggestion',body).then(res =>{
        if(res.code != -1){
          this.tableData = res.data
          this.form = Object.assign({},this.formInit)

          // lfind = arrayExistObj(this.tableData, 'id', v.id)
          // if (lfind > -1) {
          //   this.$refs['elTable'].setCurrentRow(this.tableData[lfind])
          //   this.rowClick(this.tableData[lfind])
          //   this.scrollToRow(lfind)          
          // }
          this.tableData.forEach((item, index) => {
              if (v.id == item.id) {
                this.$refs["elTable"].setCurrentRow(item);
                this.rowClick(item);
                this.scrollToRow(item)   
                this.searchup(item, index)
              }
            });
        }
      })
      
      //console.log('v,query.diagnosis',v,this.query.diagnosis)
      this.$refs['elSelectKeyWords'].focus(); //asbItemId
      this.$nextTick(() => {        
        this.$refs['elSelectKeyWords'].blur(); //total  asbItemId
        // this.query.keyWords = ''
        this.quickTableData = deepCopy(this.diagnosisAll)        
        this.$refs['elSelectKeyWords'].focus(); //total  asbItemId       
      });      
    },
    searchup(data,index) {
      this.$nextTick(()=>{
        if(index==0){
          index=1
         }
          const targetTop = this.$refs["elTable"].$el.querySelectorAll('.el-table__body tr')[index-1].getBoundingClientRect().top
      const containerTop = this.$refs["elTable"].$el.querySelector('.el-table__body').getBoundingClientRect().top
      const scrollParent = this.$refs["elTable"].$el.querySelector('.el-table__body-wrapper')
      scrollParent.scrollTop = targetTop - containerTop
      })
    },
    // 选体检类别时，定位到相应类别的第1行
    triggerScroll(){
      if(!this.query.itemTypeId) return
      let lfind = arrayExistObj(this.tableData,'itemTypeId',this.query.itemTypeId)
      if(lfind > -1){
        this.scrollToRow(lfind)
      }
    },
    scrollToRow(rowNum){
      let dom = this.$refs['elTable'].bodyWrapper
      this.$nextTick(() =>{
        let tableHeight = this.window.pageHeight < 600 ? 200 : Math.floor((this.window.pageHeight - 200) / 2)
        let rowHeight = 36.96
        dom.scrollTo(0, rowHeight * rowNum - tableHeight*rowNum/(2*this.tableData.length) ) 
      })
    },
 

    //拖拽
    rowDrop(elId) {
      this.$nextTick(() => {
        let el = document.querySelector(`#${elId} tbody`);
        //console.log('tbody', el)
        let that = this;
        Sortable.create(el, {
          handle: ".move",  // 选中class='move'的元素按住，方可拖动
          animation: 150, // ms, number 单位：ms，定义排序动画的时间
          //拖拽结束
          onChoose({ oldIndex }) {
            that.$refs["elTable"].setCurrentRow(that.tableData[oldIndex]);
            that.rowClick(that.tableData[oldIndex]);
          },
          onEnd({ newIndex, oldIndex }) {
            let currRow = that.tableData.splice(oldIndex, 1)[0];
            that.tableData.splice(newIndex, 0, currRow);
          },
        });
      });
    },

    rowClick(row){
      this.form = deepCopy(row)

      //用于选择树节点
      // if(typeof row.itemTypeId == 'string'){
      //   this.query.itemTypeId = row.itemTypeId  
      // }else{
      //   this.query.itemTypeId = row.itemTypeId[row.itemTypeId.length - 1]
      // }
      
    },

    btnAdd(){
      if(!this.query.itemTypeId){
        this.$message.warning("请先选择项目类别！")
        return
      }
      this.form = deepCopy(this.formInit)
      this.form.itemTypeId = this.query.itemTypeId
      this.dialogVisible = true
    },

    btnEdit(){
      if(!this.form.id){
        this.$message.warning("请先选择要编辑的诊断记录！")
        return
      }
      this.dialogVisible = true
    },
    ischangsItemTypeId(v){
      if(v.length>1){
        this.form.itemTypeId=this.form.itemTypeId.slice(-1)[0]
      }else{
        this.form.itemTypeId=this.form.itemTypeId[0]
      }
      this.$refs.itemTypeIds.toggleDropDownVisible();
    },
    inputDisplayName(v){
      //console.log(v)
      this.form.suggestionName = v
    },

    onSubmit(formName){
      let msg='',body = {},itemTypeId=''
      
      this.$refs[formName].validate((valid, fields) => {
        if (!valid) {
          msg = fields[Object.keys(fields)[0]][0].message;
          return false;
        }        
      })

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

      if(typeof this.form.itemTypeId == 'object'){
        itemTypeId = this.form.itemTypeId[this.form.itemTypeId.length - 1]
      }else{
        itemTypeId = this.form.itemTypeId
      }
      
      body = {
        displayName: this.form.displayName,
        itemTypeId,
        suggestionName: this.form.suggestionName,
        isIll: this.form.isIll,
        isSummaryTemplate: this.form.isSummaryTemplate,
        forSexId: this.form.forSexId,
        diagnosisLevelId: this.form.diagnosisLevelId,
        isActive:this.form.isActive,
      }
      // console.log('this.form',this.form)
      if(this.form.id){
        postapi(`/api/app/diagnosis/updatediagnosis?id=${this.form.id}`,body).then(res =>{
          if(res.code != -1){
            this.dialogVisible = false
            //this.$message.success('操作成功！')
          }
        })
      }else{
        postapi(`/api/app/diagnosis/creatediagnosis`,body).then(res =>{
          if(res.code != -1){
            this.form = Object.assign(this.form,res.data)    
            this.dialogVisible = false       
            //this.$message.success('操作成功！') 
          }
        })
      }
    },

    btnSort(){
      if(this.tableData.length<2) return
      let itemList = []
      this.tableData.forEach((e,index) =>{
        itemList.push({
          id:e.id,
          displayOrder:index+1
        })
      })

      putapi('/api/app/diagnosis/updatesortmany',{itemList}).then(res =>{
        if(res.code != -1){
          //this.$message.success('操作成功！')
        }
      })
    },

    closeDialog(){
      if(!this.form.id) return
      let curRow = {}
      let lfind = arrayExistObj(this.tableData,'id',this.form.id)
      if(lfind > -1){
        curRow = Object.assign(this.tableData[lfind],this.form)
        this.tableData[lfind] = curRow
      }else{
        lfind = this.tableData.length
        curRow = Object.assign({},this.form)
        this.tableData.push(curRow)
      }
      if(lfind > -1){
        this.$refs['elTable'].setCurrentRow(curRow)
        this.$nextTick(() =>{
          this.rowClick(curRow)
        })
      }
      this.allDiagnosis()
    },

    btnDel(){
      if(!this.form.id){
        this.$message.warning("请先选中要删除的诊断记录！")
        return
      }

      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否", 
        type: "warning",
        cancelButtonClass:"difference",
        confirmButtonClass:"commonbutton"
      }).then(() => {
        //console.log('{patientRegisterIds}',{patientRegisterIds})
        return postapi(`/api/app/diagnosis/deletediagnosis?id=${this.form.id}`);
      }).then((res) => {
        if(res.code != -1){
          let lfind = arrayExistObj(this.tableData,'id',this.form.id)
          if(lfind > -1) this.tableData.splice(lfind,1)
          this.form = deepCopy(this.formInit)   
          this.allDiagnosis()
          //this.$message.success('操作成功！')
        }          
      }).catch((err) => {
        if (err == "cancel") {
          this.$message.info("已取消操作");
        }
      });     
    },

  },

  watch: {    
    // "query.itemTypeId":{
    //   immediate: true, // 立即执行
    //   // deep: true, // 深度监听复杂类型内变化
    //   handler(newVal,oldVal){
    //     // console.log('watch:patientRegisterNo:',newVal,oldVal)
    //     if(newVal != oldVal){
    //       this.btnQuery();                 
    //     }
    //   }
    // },
    "query.triggerScroll":{
      immediate: true, // 立即执行
      // deep: true, // 深度监听复杂类型内变化
      handler(newVal,oldVal){
        // console.log('watch:patientRegisterNo:',newVal,oldVal)
        if(newVal != oldVal){
          this.btnQuery();                 
        }
      }
    },
  },
};
</script>
<style scoped>
@import '../../assets/css/global_button.css';
@import '../../assets/css/global_card.css';
@import '../../assets/css/global_dialog.css';
@import '../../assets/css/global_form.css';
@import '../../assets/css/global_input.css';
@import '../../assets/css/global_table.css';
@import '../../assets/css/global.css';

.box {
  display: flex;
  flex-direction: column;
}
/* form表单每一项的下边距 */
:deep .el-form-item {
  margin-bottom: 14px;
}
/* 去掉input textarea的手动扩张样式 */
:deep(.el-textarea__inner) {
  resize: none;
}
/* el-dialog的头部样式 */
:deep .el-dialog__header {
  padding: 11px 20px 11px;
}
/* el-dialog的主体样式 */
:deep .el-dialog__body {
  padding: 0px 20px 0px;
}
/* el-divider样式 */
:deep .el-divider--horizontal {
  margin: 0px 0 12px;
}
/* el-dialog的底部样式 */
:deep .el-dialog__footer {
  padding: 0px 20px 14px;
}
.seachinput {
  width: 250px;
  margin-right: 110px;
}
:deep .seachinput .el-select {
  width: 100%;
}
</style>
