<template>
  <div class="container">
    <div v-show="!isDetail && !isAudit">
      <direct-search
        ref="form"
        :label-position="'right'"
        :forms="searchList"
        :form-defaults="initForm"
        :style="{ textAlign: 'left' }"
        @handleSearch="handleFormSearch"
      />
      <el-table-self
        ref="table"
        :table-data="tableData"
        :columns="columns"
        :list-loading="listLoading"
        :current-page="pageIndex"
        :total-count="total"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        :sort-change="sortChange"
        @pageSizeChange="handleSizeChange"
        @currentPageChange="handleCurrentChange"
      />
    </div>

    <div v-if="isDetail">
      <div style="margin-left: 24px">
        <el-button icon="el-icon-back" @click="backInfoce">返 回</el-button>
        <span class="ml-20" style="color: red">{{ note }}</span>
      </div>
      <ConfigForms
        form-type="1"
        :patient-id="patientId"
        :disabled="disabled"
        :tab-disabled="tabDisabled"
        :is-draft="'0'"
        :operation="'edit'"
        @addMethods="addMethods"
      ></ConfigForms>
    </div>
    <audit
      v-if="isAudit"
      :form-id="curAuditDetail.formId"
      :in-patient-id="curAuditDetail.patientId"
      :inUnionName="curAuditDetail.unionName"
      @changeIsAudit="changeIsAudit"
      @submitAudit="submitAudit"
    ></audit>
  </div>
</template>

<script>
import paginationMixin from "@/components/TabComponents/mixin"
import { getPatientPage, deletePatient } from "@/api/patient.js"
import ConfigForms from "./components/ConfigForms.vue"
import audit from "@/views/audit-detail/index.vue"
import { mapGetters } from "vuex"
export default {
  name: "ScreeningIndex",
  components: { ConfigForms, audit },
  mixins: [paginationMixin],
  computed: {
    ...mapGetters({
      selectedIndex: "table/selectedIndex",
      refreshFlag: "table/refreshFlag",
      roles: "user/roles",
    }),
    initCheckStatus() {
      return this.$route.query.checkStatus
    },
  },
  data() {
    return {
      isAudit: false, //控制审核详情
      curAuditDetail: {},
      isDetail: false, //! 控制详情显隐
      listLoading: false,
      disabled: false,
      tableData: [],
      cacheForm: {},
      tabDisabled: true,
      searchList: [
        {
          type: "daterange",
          label: "筛查时间",
          prop: "CreateDate",
          placeholder: "请选择时间",
          valueFormat: "yyyy-MM-dd",
        },
        {
          label: "筛查审核状态",
          type: "select",
          prop: "checkStatus",
          opts: [
            { label: "待审核", value: "1" },
            { label: "驳回修改", value: "2" },
            { label: "合格", value: "3" },
            { label: "不合格", value: "4" },
          ],
        },
        {
          label: "风险评估结果",
          type: "select",
          prop: "riskRank",
          opts: [
            { label: "低危", value: "low" },
            { label: "中危", value: "medium" },
            { label: "高危", value: "high" },
          ],
        },
        {
          label: "性别",
          type: "select",
          prop: "sex",
          optsFormatter: () => {
            return this.dictMap && this.dictMap["d-sex"]
          },
        },
        {
          type: "input",
          label: "关键词",
          placeholder: "请输入医联体/姓名/身份证",
          prop: "keyParam",
        },
        {
          label: "筛查场景",
          type: "select",
          prop: "patientFrom",
          opts: [
            { label: "社区筛查", value: "1" },
            { label: "医院筛查", value: "2" },
            { label: "体检筛查", value: "3" },
          ],
        },
        {
          type: "button",
          value: "查询",
        },
      ],
      columns: [],
      searchForm: {},
      initForm: {},
    }
  },
  methods: {
    // 处理部分逻辑
    addMethods(v) {
      console.log(v)
      if (v.activeName == "index0") {
        let data = {
          birthday: v.form.birthday,
          sex: v.form.sex,
          survey_time: v.form.survey_time,
        }
        sessionStorage.setItem("index1Data", JSON.stringify(data))
      }
    },
    backInfoce() {
      this.$router.push({ query: {} })
      this.isDetail = false
    },
    handleView(row) {
      this.handleAdd(row, null, true, false)
    },
    handleAdd(
      { patientId, name, checkStatus, checkNote },
      index,
      disabled = false,
      tabDisabled = true
    ) {
      sessionStorage.removeItem("index1Data")
      sessionStorage.removeItem("survey_time")
      sessionStorage.removeItem("birthday")
      this.$store.commit("table/setAge", "")
      this.disabled = disabled
      this.tabDisabled = tabDisabled
      this.patientId = patientId || null
      this.name = name
      this.isDetail = true

      const status =
        checkStatus === 2 ? "驳回修改" : checkStatus === 4 ? "不合格" : ""
      this.note = status ? status + ":" + checkNote : ""
    },
    changeIsAudit() {
      this.isAudit = false
      this.curAuditDetail = {}
    },
    handleAudit(row) {
      console.log(row)
      this.curAuditDetail = row
      this.isAudit = true
    },
    submitAudit() {
      this.isAudit = false
      if (this.tableData.length == 1 && this.pageIndex != 1) {
        this.pageIndex--
      }
      this.handleSearch(this.searchForm)
    },
    deletePatient(row) {
      this.$confirm(`是否删除【${row.name}】?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deletePatient(row.patientId).then((res) => {
            if (res.code === 1) {
              this.$message({
                type: "success",
                message: "删除成功!",
              })
              if (this.tableData.length == 1 && this.pageIndex != 1) {
                this.pageIndex--
              }
              this.handleSearch()
            }
          })
        })
        .catch(() => {})
    },
    sortChange({ prop, order }) {
      const sort = order ? (order === "ascending" ? "asc" : "desc") : ""
      const sortField = order ? prop : ""
      this.handleSearch({ sortField, sort })
    },
    // 查询
    handleFormSearch(form) {
      this.searchForm = form
      this.pageIndex = 1
      this.handleSearch(form)
    },
    handleSearch(form) {
      if (this.$route.query.checkStatus) {
        this.$router.push({
          query: {},
        })
      }
      this.listLoading = true
      const params = Object.assign(this.cacheForm, form)
      const data = {}
      for (let key in params) {
        if (params[key] !== "" && params[key] !== null) {
          if (key.includes("Date") && params[key]) {
            data["start" + key] = params[key][0]
            data["end" + key] = params[key][1]
          } else {
            data[key] = params[key]
          }
        }
      }
      data.current = this.pageIndex
      data.size = this.pageSize
      data.isDraft = 0
      getPatientPage(data).then((res) => {
        this.listLoading = false
        if (res.code === 1) {
          const d = res.data
          this.tableData = d.records || []
          this.total = Number(d.total)
        }
      })
    },
  },

  watch: {
    selectedIndex(v) {
      this.handleFormSearch(this.searchForm)
    },
    refreshFlag(v) {
      if (v) {
        this.$store.commit("table/setRefreshFlag", 0)
        this.isDetail = false
        this.$nextTick(() => {
          this.handleView({
            patientId: this.patientId,
            name: "",
          })
        })
      }
    },
    initCheckStatus(v) {
      if (v) {
        this.initForm = {
          checkStatus: this.$route.query.checkStatus + "",
        }
        this.cacheForm = {}
        //   console.log(this.searchForm)
        this.handleSearch(this.initForm)
      }
      console.log("status" + v)
    },
  },
  created() {
    if (this.$route.query.checkStatus) {
      this.initForm = {
        checkStatus: this.$route.query.checkStatus + "",
      }
      this.handleSearch(this.initForm)
    } else {
      this.handleFormSearch()
    }

    // if (this.$route.path == "/screening/index") {
    //   this.tabDisabled = false
    // }
    console.log(this.$route.query.patientId)
    if (this.$route.query.patientId) {
      let patientId = this.$route.query.patientId
      this.patientId = patientId
      // this.$nextTick(() => {
      this.handleView({
        patientId: patientId,
        name: "",
      })
      // })
      console.log("有数据啊")
    }
  },
  mounted() {
    let roleList = this.roles.map((e) => e.roleCode)
    // console.log(this.$route.query.checkStatus)
    this.columns = [
      {
        label: "场景",
        minWidth: 120,
        value: "patientFrom",
        formatter: (row) => {
          return row.patientFrom == "1"
            ? "社区筛查"
            : row.patientFrom == "2"
            ? "医院筛查"
            : row.patientFrom == "3"
            ? "体检筛查"
            : "--"
        },
        sortable: "custom",
      },
      {
        label: "医联体",
        minWidth: 120,
        value: "unionName",
        formatter: (row) => {
          return row.unionName ? row.unionName : "--"
        },
        sortable: "custom",
      },
      {
        label: "姓名",
        minWidth: 120,
        formatter: (row) => {
          return row.name ? row.name : "--"
        },
        value: "name",
        sortable: "custom",
      },
      {
        label: "性别",
        minWidth: 80,
        value: "sex",
        formatter: (row) => {
          return row.sex
            ? this.$handle.formatDicList(this.dictMap["d-sex"], row.sex + "")
            : "--"
        },
        sortable: "custom",
      },
      // {
      //   label: "身份证",
      //   minWidth: 120,
      //   value: "idCard",
      //   formatter: (row) => {
      //     return row.idCard ? row.idCard : "--"
      //   },
      // },
      {
        label: "年龄",
        minWidth: 120,
        value: "age",
        formatter: (row) => {
          return row.age ? row.age : "--"
        },
        sortable: "custom",
      },
      {
        label: "筛查时间",
        minWidth: 180,
        value: "createTime",
        formatter: (row) => {
          return row.createTime ? row.createTime : "--"
        },
        sortable: "custom",
      },
      {
        label: "风险评估结果",
        minWidth: 120,
        value: "riskRank",
        formatter: (row) => {
          let riskRank = {
            low: "低危",
            medium: "中危",
            high: "高危",
          }
          return row.riskRank ? riskRank[row.riskRank] : "--"
        },
        sortable: "custom",
      },
      {
        label: "是否内镜",
        minWidth: 120,
        value: "isInnerCheck",
        sortable: "custom",
        formatter: (row) => {
          let arr = [
            { label: "否", value: "0" },
            { label: "是", value: "1" },
          ]
          let label
          if (String(row.isInnerCheck)) {
            label = arr.filter((e) => e.value == row.isInnerCheck)[0].label
          } else {
            label = "--"
          }
          return label
        },
      },
      {
        label: "筛查审核状态",
        minWidth: 120,
        value: "checkStatus",
        formatter: (row) => {
          let arr = [
            { label: "待审核", value: "1" },
            { label: "驳回修改", value: "2" },
            { label: "合格", value: "3" },
            { label: "不合格", value: "4" },
          ]
          let label
          if (row.checkStatus) {
            label = arr.filter((e) => e.value == row.checkStatus)[0].label
          } else {
            label = "--"
          }
          return label
        },
        sortable: "custom",
      },
      {
        label: "操作",
        width: 180,
        fixed: "right",
        operType: "button",
        operations: [
          {
            func: this.handleView,
            formatter(row) {
              if (row.checkStatus != 2) {
                return {
                  label: "查看",
                  type: "text",
                }
              } else {
                return {
                  label: "",
                  type: "none",
                  style: {
                    display: "none",
                  },
                }
              }
            },
          },
          {
            func: this.handleAdd,
            formatter(row) {
              if (row.checkStatus != 3 && row.checkStatus != 4) {
                return {
                  label: "修改",
                  type: "text",
                }
              } else {
                return {
                  label: "",
                  type: "none",
                  style: {
                    display: "none",
                  },
                }
              }
            },
          },
          {
            func: this.handleAudit,
            isHidden() {
              return !(
                roleList.includes("admin") || roleList.includes("auditer")
              )
            },
            formatter(row) {
              if (row.checkStatus == 1) {
                return {
                  label: "审核",
                  type: "text",
                }
              } else {
                return {
                  label: "",
                  type: "none",
                  style: {
                    display: "none",
                  },
                }
              }
            },
          },
          {
            func: this.deletePatient,
            formatter(row) {
              return {
                label: "删除",
                type: "text",
              }
            },
            style: {
              color: "#FA6400",
            },
          },
        ],
      },
    ]
  },
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  padding-bottom: 0px;
}
</style>