<template>
  <el-container>
    <el-header height="36px" style="margin-top: 8px">
      <el-select v-model="queryParam.status" style="width: 88px" @change="data.list = []">
        <el-option v-for="item in statuses" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      &nbsp;
      <el-select v-model="queryParam.delFlag" style="width: 80px" @change="data.list = []">
        <el-option v-for="item in delFlags" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      &nbsp;
      <el-select v-model="queryParam.type" style="width: 120px" @change="queryTypeChanged">
        <el-option v-for="item in types" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      &nbsp;&nbsp;编码：
      <el-input v-model="queryParam.code" style="width: 100px" clearable></el-input>
      &nbsp;&nbsp;名称：
      <el-input v-model="queryParam.name" style="width: 160px" clearable></el-input>
      <el-divider direction="vertical"></el-divider>
      <span v-if="queryParam.status === 0">
        模糊查询：
        <el-switch v-model="fuzzy" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        &nbsp;
      </span>
      <el-button icon="el-icon-search" type="primary" @click="search">检索</el-button>&nbsp; <el-button type="danger" @click="syncInjryMtch">同步工伤匹配</el-button>&nbsp;
      <span v-if="queryParam.status === 0 && queryParam.type >= 3">
        <el-button icon="el-icon-refresh" type="warning" @click="syncNewServiceOrItem"> 同步新增{{ queryParam.type === 3 ? '项目' : '耗材' }} </el-button>
      </span>
      <span v-if="queryParam.status === 1">
        <el-button type="primary" icon="el-icon-upload" @click="beforeUploadMatch">上传匹配关系</el-button>
      </span>
    </el-header>
    <el-main>
      <el-table :height="tableHeight" stripe :data="data.list" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column prop="code" label="编码"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column v-if="queryParam.type === 1" prop="serial" label="大小包装"></el-table-column>
        <el-table-column v-if="queryParam.type < 3" prop="dosage" label="剂型"></el-table-column>
        <el-table-column prop="unit" label="单位"></el-table-column>
        <el-table-column v-if="queryParam.type !== 3" prop="specification" label="规格"></el-table-column>
        <el-table-column v-if="queryParam.type === 3" prop="discription" label="内涵"></el-table-column>
        <el-table-column v-if="queryParam.type === 3" prop="standardCode" label="标准编码"></el-table-column>
        <el-table-column v-if="queryParam.type === 3" prop="price" label="价格"></el-table-column>
        <el-table-column v-if="queryParam.type < 3" prop="approvalNumber" label="批准文号"></el-table-column>
        <el-table-column v-if="queryParam.type !== 3" prop="factory" label="生产厂家"></el-table-column>
        <el-table-column v-if="queryParam.type === 3" prop="localName" label="地方名称"></el-table-column>
        <el-table-column v-if="queryParam.status === 1" prop="nationalName" label="国家名称"></el-table-column>
        <el-table-column v-if="queryParam.status === 1" prop="nationalCode" label="国家代码"></el-table-column>
        <el-table-column v-if="queryParam.status === 1" label="是否已上传">
          <template #default="scope">
            {{ cptYesOrNo(scope.row.uploadedFlag) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="modifyLocalItem(scope.row)">修改</el-button>
            <el-button v-if="queryParam.status === 1" type="text" icon="el-icon-refresh-left" @click="rvkUploadMatch(scope.row)">撤销匹配上传</el-button>
            <el-button v-if="queryParam.status === 0" type="text" icon="el-icon-aim" @click="beforeMatch(scope.row)">匹配</el-button>
            <el-button v-else type="text" icon="el-icon-close" @click="deleteMatch(scope.row)">取消匹配</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParam.currentPage"
        :page-sizes="[15, 30, 45, 70, 100]"
        :page-size="queryParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        style="margin-top: 5px"
      ></el-pagination>
    </el-main>
    <el-dialog v-model="showNationalList" width="80%" top="5vh">
      <div class="data-title">HIS数据</div>
      <el-descriptions :column="4" border>
        <el-descriptions-item>
          <template #label> 编码 </template>
          {{ data.row.code }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 名称 </template>
          {{ data.row.name }}
        </el-descriptions-item>
        <el-descriptions-item v-if="queryParam.type !== 3">
          <template #label> 大小包装 </template>
          {{ data.row.serial }}
        </el-descriptions-item>
        <el-descriptions-item v-if="queryParam.type !== 3">
          <template #label> 剂型 </template>
          {{ data.row.dosage }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 单位 </template>
          {{ data.row.unit }}
        </el-descriptions-item>
        <el-descriptions-item v-if="queryParam.type === 3">
          <template #label> 标准编码 </template>
          {{ data.row.standardCode }}
        </el-descriptions-item>
        <el-descriptions-item v-if="queryParam.type === 3">
          <template #label> 价格 </template>
          {{ data.row.price }}
        </el-descriptions-item>
        <el-descriptions-item v-if="queryParam.type !== 3">
          <template #label> 规格 </template>
          {{ data.row.specification }}
        </el-descriptions-item>
        <el-descriptions-item v-if="queryParam.type === 3">
          <template #label> 内涵 </template>
          {{ data.row.discription }}
        </el-descriptions-item>
        <el-descriptions-item v-if="queryParam.type !== 3">
          <template #label> 批准文号 </template>
          {{ data.row.approvalNumber }}
        </el-descriptions-item>
        <el-descriptions-item v-if="queryParam.type !== 3">
          <template #label> 生产厂家 </template>
          {{ data.row.factory }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="data-title">国家数据</div>
      <el-input v-show="queryParam.type === 3" clearable v-model="discription" style="width: 300px">
        <template #prepend>内涵过滤</template>
      </el-input>
      <el-input v-show="queryParam.type === 1 || queryParam.type === 4" clearable v-model="factory" style="width: 300px">
        <template #prepend>厂家过滤</template>
      </el-input>
      <el-divider v-show="queryParam.type === 4" direction="vertical"></el-divider>
      <el-input v-show="queryParam.type === 4" clearable v-model="certiNo" style="width: 320px">
        <template #prepend>注册证号过滤</template>
      </el-input>
      <el-table :height="dialogTableHeight" stripe :data="cptNationalItems">
        <el-table-column prop="nationalCode" label="国家代码"></el-table-column>
        <el-table-column prop="nationalName" label="国家名称"></el-table-column>
        <el-table-column prop="registeredDosage" label="注册剂型" v-if="queryParam.type === 1"></el-table-column>
        <el-table-column prop="actualDosage" label="实际剂型" v-if="queryParam.type === 1"></el-table-column>
        <el-table-column prop="makeRegisteredSpecification" label="注册规格" v-if="queryParam.type === 1"></el-table-column>
        <el-table-column prop="makeActualSpecification" label="实际规格" v-if="queryParam.type === 1"></el-table-column>
        <el-table-column prop="packingMaterial" label="包装材质" v-if="queryParam.type === 1"></el-table-column>
        <el-table-column prop="factory" label="生产厂家" v-if="queryParam.type === 1"></el-table-column>
        <el-table-column prop="approvalNumber" label="批准文号" v-if="queryParam.type === 1"></el-table-column>
        <el-table-column prop="drugStandardCode" label="药品本位码" v-if="queryParam.type === 1"></el-table-column>
        <el-table-column prop="classificationMark" label="归类标识" v-if="queryParam.type === 1"></el-table-column>
        <el-table-column prop="medicinalMaterialsName" label="药材名称" v-if="queryParam.type === 2"></el-table-column>
        <el-table-column prop="efficacyClass" label="功效分类" v-if="queryParam.type === 2"></el-table-column>
        <el-table-column prop="medicinalMaterialsFamily" label="药材科" v-if="queryParam.type === 2"></el-table-column>
        <el-table-column prop="medicinalMaterialsSpecies" label="药材种" v-if="queryParam.type === 2"></el-table-column>
        <el-table-column prop="medicinalParts" label="药用部位" v-if="queryParam.type === 2"></el-table-column>
        <el-table-column prop="properties" label="性味与归经" v-if="queryParam.type === 2"></el-table-column>
        <el-table-column prop="usageDosage" label="用法用量" v-if="queryParam.type === 2"></el-table-column>
        <el-table-column prop="siPolicy" label="医保" v-if="queryParam.type === 2"></el-table-column>
        <el-table-column prop="localMedicalServiceCode" label="地方代码" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="localMedicalServiceName" label="地方名称" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="projectConnotation" label="项目内涵" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="exclusions" label="除外内容" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="valuationUnit" label="计价单位" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="projectDescription" label="项目说明" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="firstClassPrice" label="一类价格" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="nineBitCode" label="9位编码" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="reimbursementFlag" label="是否报销" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="siReimbursementClass" label="报销分类" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="selfpayPercentage" label="自付比例" v-if="queryParam.type === 3"></el-table-column>
        <el-table-column prop="firstClass" label="一级分类" v-if="queryParam.type === 4"></el-table-column>
        <el-table-column prop="secondClass" label="二级分类" v-if="queryParam.type === 4"></el-table-column>
        <el-table-column prop="thirdClass" label="三级分类" v-if="queryParam.type === 4"></el-table-column>
        <el-table-column prop="siName" label="医保通用名" v-if="queryParam.type === 4"></el-table-column>
        <el-table-column prop="material" label="材质" v-if="queryParam.type === 4"></el-table-column>
        <el-table-column prop="fetures" label="特征" v-if="queryParam.type === 4"></el-table-column>
        <el-table-column prop="registrationCertificateNo" label="注册证号" v-if="queryParam.type === 4"></el-table-column>
        <el-table-column prop="factory" label="耗材企业" v-if="queryParam.type === 4"></el-table-column>
        <el-table-column prop="specificationNum" label="规格型号数" v-if="queryParam.type === 4"></el-table-column>
        <el-table-column label="匹配">
          <template #default="scope">
            <el-button circle type="success" icon="el-icon-thumb" @click="doMatch(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 12px"></div>
    </el-dialog>
    <el-drawer title="项目修改" v-model="showModifyLocalItem" direction="rtl">
      <div style="padding: 20px">
        <el-input size="small" v-model="data.row.name" clearable>
          <template #prepend>项目名称</template>
        </el-input>
        <div v-if="queryParam.type === 4">
          <el-input class="mt-12" size="small" v-model="data.row.specification" clearable>
            <template #prepend>项目规格</template>
          </el-input>
          <el-input class="mt-12" size="small" v-model="data.row.factory" clearable>
            <template #prepend>生产厂家</template>
          </el-input>
        </div>
        <div v-if="queryParam.type === 3">
          <el-input size="small" v-model="data.row.price" clearable class="mt-12">
            <template #prepend>项目金额</template>
          </el-input>
          <el-input size="small" v-model="data.row.unit" clearable class="mt-12">
            <template #prepend>项目单位</template>
          </el-input>
          <el-input size="small" v-model="data.row.standardCode" clearable class="mt-12">
            <template #prepend>标准编码</template>
          </el-input>
          <div class="m-prepend">项目内涵</div>
          <el-input class="mt-4" size="small" v-model="data.row.discription" clearable type="textarea" rows="3"></el-input>
        </div>
        <div class="drawer-footer">
          <el-button size="small" icon="el-icon-close" @click="cancelModify">取消</el-button>
          <el-button type="primary" size="small" icon="el-icon-check" @click="confirmModify"> 保存 </el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog title="请填写以下参数" v-model="showUploadPrm" width="20%">
      <div style="height: 8px"></div>
      <el-date-picker v-model="uploadPrm.beginDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="开始日期"></el-date-picker>
      <div style="height: 8px"></div>
      <el-date-picker v-model="uploadPrm.endDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="结束日期"></el-date-picker>
      <div style="height: 16px"></div>
      <el-button type="primary" icon="el-icon-check" @click="executeUploadMatch">确定上传</el-button>
    </el-dialog>
  </el-container>
</template>

<script>
import { reactive, ref } from '@vue/reactivity'
import { asyncNewNameForServicesOrItems, cancelMatch, executeMatch, selectLocalItems, selectNationalItems, updateLocalItem, synchronizeInjuryMatch } from '@/api/national-match'
import store from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed } from '@vue/runtime-core'
import { cptYesOrNo } from '@/utils/computed'
import { revokeCatalogueContrast, uploadCatalogueContrast } from '@/api/medical-insurance/si-manage'
export default {
  setup() {
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 85
    const dialogTableHeight = tableHeight * 0.8 - 160
    const statuses = initStatuses()
    const delFlags = initDelFlags()
    const types = initTypes()
    const factory = ref('')
    const certiNo = ref('')
    const discription = ref('')
    const fuzzy = ref(false)
    const data = reactive({
      total: 0,
      list: [],
      row: {},
      national: [],
    })
    const selections = ref([])
    const showUploadPrm = ref(false)
    const uploadPrm = reactive({
      type: '',
      beginDate: '',
      endDate: '',
    })

    const cptNationalItems = computed(() => {
      if (queryParam.type === 1) {
        return data.national.filter((item) => {
          return item.factory.indexOf(factory.value) !== -1
        })
      } else if (queryParam.type === 3) {
        return data.national.filter((item) => {
          return item.projectConnotation.indexOf(discription.value) !== -1
        })
      } else if (queryParam.type === 4) {
        return data.national.filter((item) => {
          return item.factory.indexOf(factory.value) !== -1 && item.registrationCertificateNo.indexOf(certiNo.value) !== -1
        })
      } else {
        return data.national.filter((item) => {
          return true
        })
      }
    })

    const queryParam = reactive({
      status: 0,
      delFlag: 0,
      type: 1,
      code: null,
      name: null,
      pageSize: 30,
      currentPage: 1,
    })

    const queryTypeChanged = (val) => {
      data.list = []
      data.national = []
      if (val === 4) {
        fuzzy.value = true
      } else {
        fuzzy.value = false
      }
    }

    const search = () => {
      selectLocalItems(queryParam)
        .then((res) => {
          data.total = res.total
          data.list = res.list
        })
        .catch(() => {
          data.list = []
        })
    }

    const handleSizeChange = (val) => {
      queryParam.pageSize = val
      search()
    }
    const handleCurrentChange = (val) => {
      queryParam.currentPage = val
      search()
    }

    const syncNewServiceOrItem = () => {
      asyncNewNameForServicesOrItems().then((res) => {
        ElMessage({
          type: 'success',
          message: res,
          duration: 2000,
          showClose: true,
        })
        search()
      })
    }

    const showModifyLocalItem = ref(false)
    const modifyLocalItem = (row) => {
      if (row.uploadedFlag === 1) {
        ElMessage({
          message: '请先撤销匹配上传再修改。',
          type: 'warning',
          showClose: true,
        })
        return
      }
      data.row = row
      showModifyLocalItem.value = true
    }
    const cancelModify = () => {
      showModifyLocalItem.value = false
      search()
    }
    const confirmModify = () => {
      updateLocalItem(data.row).then((res) => {
        ElMessage({
          type: 'success',
          message: res,
          duration: 2000,
          showClose: true,
        })
        showModifyLocalItem.value = false
      })
    }

    const showNationalList = ref(false)
    const beforeMatch = (row) => {
      if (fuzzy.value) {
        ElMessageBox.prompt('请调整关联查询的名称：', '提示', {
          inputValue: row.name,
          confirmButtonText: '查询',
          cancelButtonText: '取消',
        })
          .then(({ value }) => {
            row.fuzzyName = value
            getNationalItems(row)
          })
          .catch(() => {})
      } else {
        row.fuzzyName = row.name
        getNationalItems(row)
      }
    }

    const getNationalItems = (row) => {
      selectNationalItems(row).then((res) => {
        factory.value = ''
        data.row = row
        data.national = res
        showNationalList.value = true
      })
    }

    const doMatch = (row) => {
      const header =
        '<div style="font-weight: bold">选中的数据为：</div><div style="color: #409EFF">' +
        '本院名称：' +
        data.row.name +
        '</div>' +
        '<div style="color:red">' +
        '<div>' +
        '国家名称：' +
        row.nationalName +
        '</div>' +
        '<div>' +
        '国家代码：' +
        row.nationalCode +
        '</div>' +
        '</div>'

      const medOnly =
        '<div style="color: #409EFF; margin-top: 8px">' +
        '本院规格：' +
        data.row.specification +
        '</div>' +
        '<div style="color:red">' +
        '<div>' +
        '注册规格：' +
        row.makeRegisteredSpecification +
        '</div>' +
        '<div>' +
        '实际规格：' +
        row.makeActualSpecification +
        '</div>' +
        '</div>'

      const srvcOnly = '<div style="color: #409EAA">' + '地方名称：' + row.localMedicalServiceName + '</div>'

      const supplyOnly = '<div style="color: #409EAA">' + '注册证号：' + row.registrationCertificateNo + '</div>'

      const end = '<div style="font-weight: bold"d>是否确认匹配？</div>'

      let msg = ''
      if (queryParam.type == 3) {
        msg = header + srvcOnly + end
      } else if (queryParam.type === 4) {
        msg = header + supplyOnly + end
      } else {
        msg = header + medOnly + end
      }

      ElMessageBox.confirm(msg, '提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '确认匹配',
        cancelButtonText: '取消',
      })
        .then(() => {
          data.row.nationalCode = row.nationalCode
          data.row.nationalName = row.nationalName
          executeMatch(data.row).then((res) => {
            search()
            showNationalList.value = false
            ElMessage({
              type: 'success',
              message: res,
              duration: 2000,
              showClose: true,
            })
          })
        })
        .catch({})
    }

    const deleteMatch = (row) => {
      if (row.uploadedFlag === 1) {
        ElMessage({
          message: '请先撤销匹配上传再取消匹配。',
          type: 'warning',
          showClose: true,
        })
        return
      }
      cancelMatch(row).then((res) => {
        ElMessage({
          type: 'success',
          message: res,
          duration: 2000,
          showClose: true,
        })
        search()
      })
    }

    const handleSelectionChange = (val) => {
      selections.value = val
    }

    const beforeUploadMatch = () => {
      if (selections.value.length === 0) {
        ElMessage({
          message: '请选择要上传的条目！',
          type: 'warning',
          showClose: true,
        })
        return
      }
      uploadPrm.type = queryParam.type
      showUploadPrm.value = true
    }

    const executeUploadMatch = () => {
      if (!uploadPrm.beginDate || !uploadPrm.endDate) {
        ElMessage({
          message: '请填写开始日期和结束日期。',
          type: 'warning',
          showClose: true,
        })
        return
      }
      uploadPrm.list = selections
      uploadCatalogueContrast(uploadPrm).then((res) => {
        ElMessage({
          message: res,
          type: 'success',
          showClose: true,
        })
        showUploadPrm.value = false
      })
    }

    const rvkUploadMatch = (row) => {
      uploadPrm.type = queryParam.type
      uploadPrm.chargeCode = row.code
      uploadPrm.nationalCode = row.nationalCode
      revokeCatalogueContrast(uploadPrm).then((res) => {
        ElMessage({
          message: res,
          type: 'success',
          showClose: true,
        })
      })
    }

    const syncInjryMtch = () => {
      synchronizeInjuryMatch().then((res) => {
        ElMessage({
          message: res,
          type: 'success',
          showClose: true,
        })
      })
    }

    return {
      factory,
      certiNo,
      discription,
      tableHeight,
      dialogTableHeight,
      statuses,
      delFlags,
      types,
      queryParam,
      data,
      fuzzy,
      showNationalList,
      cptNationalItems,
      showModifyLocalItem,
      showUploadPrm,
      uploadPrm,
      cptYesOrNo,
      queryTypeChanged,
      search,
      syncNewServiceOrItem,
      handleSizeChange,
      handleCurrentChange,
      modifyLocalItem,
      cancelModify,
      confirmModify,
      beforeMatch,
      doMatch,
      deleteMatch,
      handleSelectionChange,
      beforeUploadMatch,
      rvkUploadMatch,
      executeUploadMatch,
      syncInjryMtch,
    }
  },
}

function initStatuses() {
  return [
    { code: 0, name: '未匹配' },
    { code: 1, name: '已匹配' },
  ]
}

function initDelFlags() {
  return [
    { code: 0, name: '启用' },
    { code: 1, name: '停用' },
  ]
}

function initTypes() {
  return [
    { code: 1, name: '西药/中成药' },
    { code: 2, name: '中草药' },
    { code: 3, name: '项目' },
    { code: 4, name: '耗材' },
  ]
}
</script>

<style scoped>
.data-title {
  padding: 8px 0;
  font-size: 16px;
  color: #333;
  font-weight: bold;
}
.mt-4 {
  margin-top: 4px;
}
.mt-12 {
  margin-top: 12px;
}
.m-prepend {
  margin-top: 12px;
  height: 28px;
  line-height: 28px;
  background-color: #f5f7fa;
  color: #909399;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 20px;
}
.drawer-footer {
  margin-top: 16px;
  width: 100%;
  text-align: end;
}
</style>
