<template>
  <div>
    <div style="display: flex;">
      <div :style="`width:${sumWidth}px;`">
        <el-table id="tableSummary" row-key="id" :data="doctorCheck.checkSummaryList" size="samll" :height="sumHeight"
          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 }"
                  :disabled="doctorBtnDisabled('delSum')" placeholder="请输入小结">
                </el-input>
                <el-button type="danger" style="min-width:23px;padding:2px;" icon="el-icon-delete"
                  @click="delSum(scope.$index)" :disabled="doctorBtnDisabled('delSum')" size="small"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div
        :style="`display: flex;position: absolute; top:${window.pageHeight - sumHeight - 38}px;right:${sumWidth + 125}px;z-index: 1;`">
        <div v-show="checkPagePriv(pagePriv.privs, '生成小结')">
          <el-button type="primary" class="btnClass" @click="btnMakeDiagnosis"
            :disabled="doctorBtnDisabled('btnMakeDiagnosis')">生成小结</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '新增小结')">
          <el-button type="primary" class="btnClass" @click="addSummary"
            :disabled="doctorBtnDisabled('addSummary')">新增小结</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '保存结果')">
          <el-button type="primary" class="btnClass" @click="save"
            :disabled="doctorBtnDisabled('save')">保存结果</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '审核')">
          <el-button type="primary" class="btnClass" style="min-width: 40px;" @click="audit"
            :disabled="doctorBtnDisabled('audit')">审核</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '排队')">
          <el-button type="primary" class="btnClass" style="min-width: 40px;" @click="fnQueue"
            :disabled="doctorBtnDisabled('fnQueue')">排队</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '危急值')">
          <el-button type="primary" class="btnClass" style="min-width: 40px;" @click="btnCritical"
            :disabled="doctorBtnDisabled('btnCritical')">危急值</el-button>
        </div>
      </div>

      <div
        :style="`display: flex;position: absolute; top:${window.pageHeight - sumHeight - 38}px;right:125px;z-index: 1;`">
        <div v-show="checkPagePriv(pagePriv.privs, '新增建议')">
          <el-button type="primary" class="btnClass" @click="addSuggestion"
            :disabled="doctorBtnDisabled('addSuggestion')">新增建议</el-button>
        </div>
      </div>
      <div :style="`margin-left:2px;width:${sumWidth}px;`">
        <el-table id="tableSuggestion" row-key="id" :data="doctorCheck.checkSuggestionList" size="samll"
          :height="sumHeight" width="100%" border>
          <el-table-column width="30" align="center">
            <template slot-scope="scope">
              <el-tag class="moveSuggestion" 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="suggestion" 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.suggestion" :autosize="{ minRows: 1, maxRows: 100 }"
                  :disabled="doctorBtnDisabled('delSug')" placeholder="请输入建议">
                </el-input>
                <el-button type="danger" style="min-width:23px;padding:2px;" icon="el-icon-delete"
                  @click="delSug(scope.$index)" :disabled="doctorBtnDisabled('delSug')" size="small"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </div>

    <div>
      <!-- 分诊排队 -->
      <el-dialog title="分诊排队" :visible.sync="dialogWin.queue" width="800px" :append-to-body="true"
        :close-on-click-modal="false">
        <Queue :refParams="queueParams" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import Sortable from "sortablejs";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { getPagePriv, checkPagePriv, deepCopy } from "../../utlis/proFunc";
import Queue from "../../components/queue/Queue.vue";

export default {
  components: {
    Queue
  },
  props: ["registerCheckId", "isCheckPicture", "optGrant", "addSummary", "btnMakeDiagnosis", "save", "audit", "unAudit", "btnLineUp", "doctorBtnDisabled"],
  data() {
    return {
      queueParams: {},
      pagePriv: {
        routeUrlorPageName: 'doctorCheck', //当前页面归属路由或归属页面权限名称
        privs: [], // 页面权限        
      },
    };
  },

  created() {
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem('userPriv')
    if (userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))
  },

  //挂载完成
  mounted() {
    this.rowDrop();
    this.rowDropSuggestion()
  },

  computed: {
    ...mapState(['window', 'dataTransOpts', 'dict', 'doctorCheck','dialogWin']),

    //小结宽度
    sumWidth() {
      return Math.floor((this.window.pageWidth - 200 - 110 - 15 - 4) / 2);
    },

    //小结高度
    sumHeight() {
      let fixHeight = this.window.pageHeight < 600 ? 600 : this.window.pageHeight
      return Math.floor((fixHeight - 120 - (this.isCheckPicture ? 110 : 0)) * 2 / 5);
    }

  },

  methods: {
    checkPagePriv,
    //获取小结
    checkSummaryList(RegisterCheckId) {
      this.doctorCheck.checkSummaryList = [];
      if (!RegisterCheckId) return;
      // console.log(`/api/app/registerchecksummary/getregisterchecksummarylist?RegisterCheckId=${RegisterCheckId}`)
      getapi(`/api/app/registerchecksummary/getregisterchecksummarylist?RegisterCheckId=${RegisterCheckId}`)
        .then((res) => {
          console.log("checkSummaryList", res.data);
          if (res.code != -1) {
            this.doctorCheck.checkSummaryList = res.data;
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `操作失败，原因：${err}` });
        });
    },

    //获取建议
    checkSuggestionList(RegisterCheckId) {
      if (!RegisterCheckId) {
        this.doctorCheck.checkSuggestionList = [];
        return;
      }
      // console.log(`/api/app/registerchecksuggestion/getregisterchecksuggestionlist?RegisterCheckId=${RegisterCheckId}`)
      getapi(`/api/app/registerchecksuggestion/getregisterchecksuggestionlist?RegisterCheckId=${RegisterCheckId}`)
        .then((res) => {
          console.log("checkSuggestionList", res.data);
          if (res.code != -1) {
            this.doctorCheck.checkSuggestionList = res.data;
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `操作失败，原因：${err}` });
        });
    },


    //拖拽
    rowDrop() {
      this.$nextTick(() => {
        const el = document.querySelector("#tableSummary tbody");
        console.log('el0', el)
        const that = this;
        Sortable.create(el, {
          handle: ".moveSummary",
          animation: 150, // ms, number 单位：ms，定义排序动画的时间
          // 开始拖拽的时候
          onStart: (evt) => {
            if (this.doctorCheck.RegisterCheckEdit.completeFlag != '0') {
              this.$alert("项目已检或弃检，不可执行此操作！", { showClose: false })
              return false
            }
          },
          //拖拽结束
          onEnd({ newIndex, oldIndex }) {
            that.isshow = false;
            const currRow = that.doctorCheck.checkSummaryList.splice(oldIndex, 1)[0];
            that.doctorCheck.checkSummaryList.splice(newIndex, 0, currRow);
            console.log('el', el)
          },
        });
      });
    },

    //拖拽
    rowDropSuggestion() {
      this.$nextTick(() => {
        const el = document.querySelector("#tableSuggestion tbody");
        //console.log('tbody',tbody)
        const that = this;
        Sortable.create(el, {
          handle: ".moveSuggestion",
          animation: 150, // ms, number 单位：ms，定义排序动画的时间
          // 开始拖拽的时候
          onStart: (evt) => {
            if (this.doctorCheck.RegisterCheckEdit.completeFlag != '0') {
              this.$alert("项目已检或弃检，不可执行此操作！", { showClose: false })
              return false
            }
          },
          //拖拽结束
          onEnd({ newIndex, oldIndex }) {
            that.isshow = false;
            const currRow = that.doctorCheck.checkSuggestionList.splice(oldIndex, 1)[0];
            that.doctorCheck.checkSuggestionList.splice(newIndex, 0, currRow);
          },
        });
      });
    },

    // 分诊排队
    fnQueue() {
      if (!this.dataTransOpts.tableS.patient_register.id) {
        this.$message.warning({ showClose: true, message: '未获取到人员信息' })
        return
      }

      this.queueParams = {
        patientRegisterId: this.dataTransOpts.tableS.patient_register.id
      }
      this.dataTransOpts.plus.queue++
      this.dialogWin.queue = true
    },

    // 危急值
    btnCritical(){
      this.dialogWin.FollowCriticalCheck = true
    },

    //删除小结
    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('已取消删除')
        }
      });
    },

    addSuggestion() {
      this.doctorCheck.checkSuggestionList.push({
        id: Math.random(),
        registerCheckId: this.doctorCheck.RegisterCheckEdit.id,
        suggestion: '',
      })
    },


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

  },

  //监听事件
  watch: {
    //检查项目切换
    // "doctorCheck.RegisterCheckId"(newVal, oldVal) {
    //   console.log("watch doctorCheck.RegisterCheckId newVal：", newVal, " oldVal：", oldVal);      
    //   this.checkSummaryList(newVal)
    //   this.checkSuggestionList(newVal)      
    // },
    //检查项目未切换换时 也可以强制刷新数据
    "dataTransOpts.refresh.register_check.S": {
      immediate: true,
      handler(newVal, oldVal) {
        console.log(`watch 小结 newVal:${newVal} oldVal:${oldVal} registerCheckId: ${this.dataTransOpts.tableS.register_check.id}`);
        this.checkSummaryList(this.dataTransOpts.tableS.register_check.id)
        this.checkSuggestionList(this.dataTransOpts.tableS.register_check.id)
      }
    },

  },
};
</script>
<style scoped>
@import '../../assets/css/global_table.css';

.btnClass {
  margin-left: 2px;
  height: 22px;
  padding: 2px 2px;
  /*原始 默认值 500 */
}

::v-deep .el-textarea__inner {
  min-height: 23px;
  height: 23px;
  line-height: 1.25;
  padding: 1px 15px 1px 2px;
}
</style>