<template>
  <page-layer>
    <template #header>
      <el-input size="small" placeholder="姓名" @keyup.enter="query" v-model="queryTerm.name" clearable
                prefix-icon="Search" style="width: 300px">
        <template #prepend>姓名</template>
      </el-input>
      <el-date-picker v-model="queryTerm.executeDate" type="date" size="small"
                      placeholder="选择预约日期"></el-date-picker>
      <el-button type="primary" style="margin-left: 10px" icon="Search" @click="query">查询</el-button>
      <el-button type="primary" v-show="data.list.length" icon="Download" @click="excel">导出excel</el-button>
      <el-button type="success" icon="CirclePlusOutline" @click="xinZengYiMiaoDialog = true">新增疫苗</el-button>
      <el-button type="info" icon="Tools" @click="openMaintain" style="margin-left: 10px">疫苗数据维护</el-button>
    </template>
    <template #main>
      <el-table :data="data.list" stripe highlight-current-row>
        <el-table-column prop="patientId" width="70" label="门诊id"></el-table-column>
        <el-table-column prop="name" width="50" label="姓名"></el-table-column>
        <el-table-column width="50" label="性别" prop="sex">
          <template #default="scope">
            {{ cptSex(scope.row.sex) }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" width="120" label="联系电话"></el-table-column>
        <el-table-column prop="socialNo" width="200" label="身份证号"></el-table-column>
        <el-table-column prop="age" width="50" label="年龄"></el-table-column>
        <el-table-column prop="corpName" show-overflow-tooltip label="工作单位"></el-table-column>
        <el-table-column prop="jobCategoryToString" show-overflow-tooltip label="工作性质"></el-table-column>
        <el-table-column prop="executeDate" label="预约接种时间"></el-table-column>
        <el-table-column prop="vaccinateCode" label="产品编码"></el-table-column>
        <el-table-column prop="vaccinateName" show-overflow-tooltip label="产品名称"></el-table-column>
        <el-table-column prop="vaccinateFactory" show-overflow-tooltip label="疫苗厂商"></el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryTerm.currentPage"
          :page-sizes="[20, 30, 40, 50, 100]"
          :page-size="queryTerm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
          style="margin-top: 5px"
      ></el-pagination>
      <!-- 新增疫苗 -->
      <el-dialog title="新增疫苗" v-model="xinZengYiMiaoDialog">
        <el-form label-width="100px" :rules="yiMiaoRules" ref="yiMiaoForm" :model="newVaccines">
          <el-form-item label="疫苗名称：" prop="name">
            <el-input v-model="newVaccines.name" clearable show-word-limit maxlength="32"
                      @blur="newVaccines.name = $event.target.value.trim()"></el-input>
          </el-form-item>
          <el-form-item label="可否预约：" prop="enableFlag">
            <el-switch
                v-model="newVaccines.enableFlag"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="开启"
                inactive-text="关闭"
                :active-value="1"
                :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="预约提示：" prop="bookTip">
            <el-input
                type="textarea"
                clearable
                :rows="4"
                v-model="newVaccines.bookTip"
                show-word-limit
                maxlength="120"
                @blur="newVaccines.bookTip = $event.target.value.trim()"
            ></el-input>
          </el-form-item>
          <el-button type="success" @click="yiMiaoFormSubmit()">保存</el-button>
          <el-button type="info" @click="resetForm(yiMiaoForm)">重置</el-button>
        </el-form>
      </el-dialog>
      <!-- 添加疫苗厂家 -->
      <el-drawer title="添加厂家" v-model="xinZengChangJiaDrawer" size="50%" :before-close="handleClose">
        <div style="width: 80%">
          <el-form label-width="100px" :rules="changJiaRules" :model="covidVaccinateFactory"
                   ref="covidVaccinateFactoryForm">
            <el-form-item label="产品编码" prop="code">
              <el-input v-model="covidVaccinateFactory.code"></el-input>
            </el-form-item>
            <el-form-item label="厂家名称" prop="name">
              <el-input v-model="covidVaccinateFactory.name"
                        @blur="covidVaccinateFactory.name = $event.target.value.trim()"></el-input>
            </el-form-item>
            <el-form-item label="规格" prop="specification" show-word-limit maxlength="16">
              <el-input v-model.trim="covidVaccinateFactory.specification"
                        @blur="covidVaccinateFactory.specification = $event.target.value.trim()"></el-input>
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input v-model="covidVaccinateFactory.price"></el-input>
            </el-form-item>

            <el-form-item label="可否预约：" prop="enableFlag">
              <el-switch
                  v-model="covidVaccinateFactory.enableFlag"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="开启"
                  inactive-text="关闭"
                  :active-value="1"
                  :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
            <el-button type="success" @click="submitChangJia" style="margin-left: 20px">新增</el-button>
          </el-form>
        </div>
        <el-divider></el-divider>
        <el-table :data="tableChangJia" >
          <el-table-column label="编码" prop="code"></el-table-column>
          <el-table-column label="厂家名称" prop="name"></el-table-column>
          <el-table-column label="规格" prop="specification"></el-table-column>
          <el-table-column label="价格" prop="price"></el-table-column>
          <el-table-column label="可否预约" prop="enableFlag">
            <template #default="scope">
              <span v-html="enableFlagToString(scope.row.enableFlag)"></span>
            </template>
          </el-table-column>
          <el-table-column label="删除">
            <template #default="scope">
              <el-button type="danger" size="small" @click="shanchu(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="success" style="margin-left: 20px; margin-top: 20px" v-show="tableChangJia.length > 0"
                   @click="baoCunChangJia">保存
        </el-button>
      </el-drawer>
      <!-- 新冠疫苗数据维护 -->
      <el-dialog title="新冠疫苗数据维护" v-model="xinGuanYiMiaoShuJuWeiHu" @close="closeXinGuanYiMiaoShuJuWeiHuDialog"
                 fullscreen>
        <VccntMaintain :init="initProp"/>
      </el-dialog>
    </template>
  </page-layer>
</template>

<script>
import {reactive, ref, unref} from '@vue/reactivity'
import {formatDate} from '@/utils/date'
import {
  queryXGYM,
  xinZengChangJia,
  xinZengYiMiao,
  yiJianXiuGaiRiQi
} from '@/api/querydata/query-covidVaccinateAppointment'
import store from '@/store'
import {ElMessage, ElMessageBox} from 'element-plus'
import {downloadExcel} from '@/utils/excel'
import {computed, onMounted} from 'vue'
import {cptSex, enableFlagToString} from '@/utils/computed'
import VccntMaintain from './XinGuanYiMiaoWeiHu.vue'
import {clone} from '@/utils/clone'
import PageLayer from "@/layout/PageLayer";

export default {
  name: 'CovidVaccinateAppointment',
  components: {
    PageLayer,
    VccntMaintain,
  },
  setup() {
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 100

    const queryTerm = reactive({
      name: '',
      executeDate: '',
      pageSize: 30,
      currentPage: 1,
    })
    const data = reactive({
      list: [],
      total: 0,
    })
    const handleSizeChange = (val) => {
      queryTerm.pageSize = val
      queryXGYM(queryTerm).then((res) => {
        data.list = res.data
      })
    }
    const handleCurrentChange = (val) => {
      queryTerm.currentPage = val
      queryXGYM(queryTerm).then((res) => {
        data.list = res.data
      })
    }

    const xianZhiYuYue = ref([])

    //根据产品编码的code来搜索
    const changJiaCode = ref('')
    //根据产品编码的code来搜索
    const cptTable = computed(() => {
      return xianZhiYuYue.value.filter((item) => {
        return item.code.toString().indexOf(changJiaCode.value) > -1
      })
    })

    //打开查看阈值的抽屉
    const sheZhiYuZhiTitle = ref('')

    //对应厂家阈值的数组 放入table中查看
    const yuZhiTabel = ref([])

    //这个是修改单个阈值触发的 计数框 只有输入框的值改变就会触发这个事件
    const handleChange = (value, scope) => {
      let reg = /^[0-9]+$/
      if (!reg.test(value)) {
        ElMessage({
          type: 'error',
          message: '只能输入整数',
          showClose: true,
          duration: 2500,
        })
        return
      }
      //修改阈值
      let list = [{id: scope.row.id, value: value}]
      ElMessageBox.confirm('确认要修改日期为：<span style="color:teal">' + scope.row.date + '</span> 的阈值', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'info',
      })
          .then(() => {
            yiJianXiuGaiRiQi(list)
          })
          .catch(() => {
          })
    }
    //一键修改全部的日期
    const yiJianXiuGaiRiQiValue = ref(undefined)
    //这个是一键修改全部的
    const yiJianXiuGaiRiQiSubmit = (value) => {
      ElMessageBox.confirm('是否要统一修改', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
          .then(() => {
            let reg = /^[0-9]+$/
            if (!reg.test(value)) {
              ElMessage({
                type: 'error',
                message: '只能输入整数',
                showClose: true,
                duration: 2500,
              })
              return
            }
            let list = []
            for (let i = 0; i < yuZhiTabel.value.length; i++) {
              list.push({id: yuZhiTabel.value[i].id, value: value})
            }
            yiJianXiuGaiRiQi(list).then((res) => {
              yiJianXiuGaiRiQiValue.value = undefined
            })
          })
          .catch(() => {
          })
    }

    onMounted(() => {
      queryTerm.executeDate = new Date()
    })

    const query = () => {
      if (queryTerm.executeDate !== null) {
        queryTerm.executeDate = formatDate(queryTerm.executeDate)
      } else {
        queryTerm.executeDate = ''
      }
      if (queryTerm.executeDate === '' && queryTerm.name === '') {
        ElMessage.warning({
          titel: '提示',
          message: '至少填写一项',
          showClose: true,
          duration: 2000,
        })
        return
      }
      queryXGYM(queryTerm)
          .then((res) => {
            data.list = res.data
            data.total = res.total
          })
          .catch(() => {
            data.list = []
          })
    }
    //这个是从后端导
    const excel = () => {
      store.commit('app/setLoading', true)
      const data = {
        param: {
          currentPage: 1,
          pageSize: -1,
          executeDate: queryTerm.executeDate,
          name: queryTerm.name,
        },
        url: '/CovidVaccinateAppointment/exportExcel',
        fileName: queryTerm.name === '' ? queryTerm.executeDate + '预约人数.xlsx' : '人员:' + queryTerm.name + '.xlsx',
      }
      setTimeout(() => {
        downloadExcel(data)
      }, 500)
    }

    /**
     * 点击新增疫苗
     */
        //点击打开 log
    const xinZengYiMiaoDialog = ref(false)

    const yiMiaoForm = ref(null)

    const newVaccines = reactive({
      name: '',
      enableFlag: 0,
      bookTip: '',
    })

    //产品code的验证
    const code = (rule, value, callback) => {
      let reg = /^\d+$/
      let flag = false
      for (let i = 0; i < tableChangJia.value.length; i++) {
        if (tableChangJia.value[i].code.toString() === value) {
          flag = true
          break
        }
      }
      if (flag) {
        callback(new Error('编码已存在不要重复添加'))
      } else if (!value) {
        callback(new Error('编码不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('只能输入数字，且不能带有小数点'))
      } else if (value.length > 9) {
        callback(new Error('编码超长'))
      } else {
        callback()
      }
    }
    //验证厂家的名字不能一致
    const factoryName = (rule, value, callback) => {
      let flag = false
      for (let i = 0; i < tableChangJia.value.length; i++) {
        if (tableChangJia.value[i].name.toString() === value) {
          flag = true
          break
        }
      }
      if (!value) {
        callback(new Error('不能为空'))
      } else if (flag) {
        callback(new Error('厂家名字已存在无法重复添加'))
      } else {
        callback()
      }
    }
    //疫苗的表单验证
    const yiMiaoRules = ref({
      id: [{required: true, message: '疫苗id不能为空', trigger: 'blur'}],
      name: [
        {required: true, message: '疫苗名称不能为空', trigger: 'blur'},
        {min: 3, max: 32, message: '长度在 3 到 32 个字', trigger: 'blur'},
      ],
      enableFlag: [{required: true, message: '至少选中一项', trigger: 'blur'}],
      bookTip: [
        {required: true, message: '不能为空', trigger: 'blur'},
        {min: 3, max: 120, message: '长度在 3 到 120 个字', trigger: 'blur'},
      ],
    })

    //厂家的表单验证
    const changJiaRules = ref({
      price: [
        {required: true, trigger: 'blur', message: '价格不能为空'},
        {
          pattern: /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/,
          message: '请输入正确的价格',
          trigger: 'blur',
        },
      ],
      name: [{required: true, trigger: 'blur', validator: factoryName}],
      specification: [
        {required: true, message: '规格不能为空', trigger: 'blur'},
        {min: 1, max: 16, message: '规格字数在 1 ~ 16', trigger: 'blur'},
      ],
      code: [{required: true, trigger: 'blur', validator: code}],
      enableFlag: [{required: true, message: '至少选中一项', trigger: 'blur'}],
    })

    //提交添加疫苗信息 添加成功后 打开添加厂家的 抽屉并且把这个疫苗的id 给到vaccinateId 因为这两个表是要关联的
    const yiMiaoFormSubmit = async () => {
      let form = unref(yiMiaoForm)
      if (!form) return
      try {
        await form.validate()
        //这里会返回一个 添加成功的id
        ElMessageBox.confirm('是否要添加<span style="color:teal">【' + newVaccines.name + '】</span>的疫苗', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'info',
        })
            .then(() => {
              xinZengYiMiao(newVaccines).then((res) => {
                covidVaccinateFactory.vaccinateId = res
                xinZengChangJiaDrawer.value = true
              })
            })
            .catch(() => {
            })
      } catch (error) {
      }
    }
    //点击重置数据 一个是重置疫苗的数据 一个是重置厂家的数据
    //当重置 疫苗数据的时候需要把厂家 疫苗表的id 给清空
    const resetForm = (formName) => {
      if (formName === 'formName') {
        covidVaccinateFactory.vaccinateId = 0
      }
      unref(formName).resetFields()
    }

    //新增疫苗厂家的抽屉
    const xinZengChangJiaDrawer = ref(false)

    const covidVaccinateFactoryForm = ref(null)

    //厂家实体类
    const covidVaccinateFactory = reactive({
      code: '',
      specification: '',
      vaccinateId: 0,
      price: 0,
      name: '',
      enableFlag: 0,
    })
    //厂家要先添加到表格中
    const tableChangJia = ref([])
    //点击添加厂家的按钮
    const submitChangJia = async () => {
      let form = unref(covidVaccinateFactoryForm)
      if (!form) return
      try {
        await form.validate()
        tableChangJia.value.push(clone(covidVaccinateFactory))
        resetForm(covidVaccinateFactoryForm)
      } catch (e) {
      }
    }

    //点击删除按钮 删除掉厂家表格中的数据 tableChangJia这个表
    const shanchu = (index) => {
      tableChangJia.value.splice(index, 1)
    }

    const tianJiaChangJiaFlag = ref(false)

    //点击保存 添加疫苗厂家
    const baoCunChangJia = () => {
      tianJiaChangJiaFlag.value = true
      if (covidVaccinateFactory.vaccinateId !== 0) {
        xinZengChangJia(tableChangJia.value).then((res) => {
          xinZengChangJiaDrawer.value = false
        })
      } else {
        ElMessage({
          type: 'error',
          message: '请新增疫苗',
          showClose: true,
          duration: 2500,
        })
      }
    }

    //在关闭添加厂家 抽屉 执行的操作
    const handleClose = (done) => {
      if (tianJiaChangJiaFlag.value) {
        tianJiaChangJiaFlag.value = false
        tableChangJia.value = []
        done()
      } else {
        ElMessageBox.alert('至少添加一项厂家，新增后点击保存', '提示', {
          confirmButtonText: '确定',
          type: 'error',
        })
            .then(() => {
            })
            .catch(() => {
            })
      }
    }

    const xinGuanYiMiaoShuJuWeiHu = ref(false)
    const initProp = ref(0)

    const openMaintain = () => {
      initProp.value += 1
      xinGuanYiMiaoShuJuWeiHu.value = true
    }

    const closeXinGuanYiMiaoShuJuWeiHuDialog = () => {
      xinGuanYiMiaoShuJuWeiHu.value = false
    }

    return {
      queryTerm,
      query,
      data,
      tableHeight,
      handleSizeChange,
      handleCurrentChange,
      excel,
      xianZhiYuYue,
      cptSex,
      xinZengYiMiaoDialog,
      newVaccines,
      yiMiaoRules,
      changJiaRules,
      yiMiaoFormSubmit,
      resetForm,
      xinZengChangJiaDrawer,
      covidVaccinateFactory,
      submitChangJia,
      tableChangJia,
      shanchu,
      enableFlagToString,
      baoCunChangJia,
      handleClose,
      changJiaCode,
      cptTable,
      yuZhiTabel,
      handleChange,
      yiJianXiuGaiRiQiSubmit,
      yiJianXiuGaiRiQiValue,
      yiMiaoForm,
      covidVaccinateFactoryForm,
      sheZhiYuZhiTitle,
      xinGuanYiMiaoShuJuWeiHu,
      closeXinGuanYiMiaoShuJuWeiHuDialog,
      initProp,
      openMaintain,
    }
  },
}
</script>

<style></style>
