<template>
  <el-container>
    <el-header height="36px" style="margin-top: 8px">
      <el-input size="small" placeholder="疫苗名称" v-model="vaccineName" clearable style="width: 300px">
        <template #prepend>疫苗名称</template>
      </el-input>
      <el-button v-show="newVaccines.id > 0" style="margin-left: 20px" type="success" @click="xiuGaiSubmit">修改疫苗信息</el-button>
      <el-button v-show="newVaccines.id > 0" @click="addOrModify(1, null)">新增该疫苗厂家信息</el-button>
    </el-header>
    <el-container>
      <el-aside>
        <el-table :height="tableHeight" :data="cptTable" @row-click="clickRow" stripe highlight-current-row>
          <el-table-column label="本院编码" width="70" prop="id"></el-table-column>
          <el-table-column label="疫苗名称" width="150" show-overflow-tooltip prop="name"></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>
      </el-aside>
      <el-main>
        <el-form label-width="100px" :model="newVaccines" :rules="yiMiaoRules" ref="yiMiaoForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="本院id：" prop="id">
                <el-input disabled v-model="newVaccines.id"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <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-col>
            <el-col :span="12">
              <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-col>
            <el-col :span="12">
              <el-form-item label="预约提示：" prop="bookTip">
                <el-input
                  v-model="newVaccines.bookTip"
                  type="textarea"
                  :rows="4"
                  show-word-limit
                  maxlength="120"
                  @blur="newVaccines.bookTip = $event.target.value.trim()"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="changJiaTable" :height="tableHeight - 200" stripe highlight-current-row>
          <el-table-column label="产品编码" prop="code" width="100"></el-table-column>
          <el-table-column label="疫苗厂商" show-overflow-tooltip 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">
              <el-switch
                v-model="scope.row.enableFlag"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="启用"
                @click="kaiQiGaiChangJiaYuYueClick(scope.row)"
                inactive-text="停用"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="阈值">
            <template #default="scope">
              日期：{{ scope.row.date }} <br />
              阈值：
              <el-input-number
                style="width: 80px"
                v-model="scope.row.value"
                :controls="false"
                :min="0"
                :max="150"
                @change="(value) => handleChange(value, scope)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button class="el-icon-edit" @click="addOrModify(2, scope.row)" type="success">修改</el-button>
              <!-- <el-button class="el-icon-delete" @click="shanChuChangJiaSubmit(scope.row.code)" type="info">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <!-- 删除和修改的抽屉 -->
      <el-drawer :title="addOrModifyTitle" v-model="openAddOrModify" size="40%">
        <div style="width: 90%">
          <el-form label-width="100px" :rules="changJiaRules" :model="covidVaccinateFactory" ref="covidVaccinateFactoryForm">
            <el-form-item label="产品编码" prop="code">
              <el-input v-model="covidVaccinateFactory.code" :disabled="flag === 2" clearable></el-input>
            </el-form-item>
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="covidVaccinateFactory.name" clearable show-word-limit maxlength="32" @blur="covidVaccinateFactory.name = $event.target.value.trim()"></el-input>
            </el-form-item>
            <el-form-item label="规格" prop="specification">
              <el-input
                v-model="covidVaccinateFactory.specification"
                show-word-limit
                maxlength="16"
                clearable
                @blur="covidVaccinateFactory.specification = $event.target.value.trim()"
              ></el-input>
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input v-model="covidVaccinateFactory.price" clearable></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" v-show="flag === 1" @click="submitChangJia()" style="margin-left: 20px">新增</el-button>
            <el-button type="success" v-show="flag === 2" @click="xiuGaiChangJiaBaoCun" style="margin-left: 20px">保存</el-button>
          </el-form>
        </div>
        <el-table style="margin: 20px auto auto 20px" v-if="covidVaccinateFactory.code !== null" :data="changJiaYuZhiList" height="50%">
          <el-table-column label="近七日阈值设置">
            <el-table-column label="排序" type="index"></el-table-column>
            <el-table-column label="日期" prop="date"></el-table-column>
            <el-table-column label="阈值" prop="value">
              <template #default="scope">
                <el-input-number v-model="scope.row.value" :controls="false" :min="0" :max="150" @change="(value) => handleChange(value, scope)"></el-input-number>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </el-drawer>
    </el-container>
  </el-container>
</template>

<script>
import { ref, unref } from '@vue/reactivity'
import store from '@/store'
import { computed, watchEffect } from 'vue'
import {
  chaKanChangJia,
  chaKanYiMiao,
  xiuGaiYiMiao,
  xinZengChangJia,
  xiuGaiChangJia,
  shanChuChangJia,
  queryChangJiaDuiYingDeYuZhi,
  yiJianXiuGaiRiQi,
  kaiQiHuoGuanBiYuYue,
} from '@/api/querydata/query-covidVaccinateAppointment'
import { enableFlagToString } from '@/utils/computed'
import { clone } from '@/utils/clone'
import { ElMessageBox, ElNotification } from 'element-plus'
export default {
  props: {
    init: {
      type: Number,
      default: -1,
    },
  },
  setup(props) {
    watchEffect(() => {
      if (props.init) {
        chaKanYiMiao().then((res) => {
          yiMiaoTable.value = res
        })
      }
    })

    const vaccineName = ref('')
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 40

    //全部的疫苗放入表格中
    const yiMiaoTable = ref([])

    //根据疫苗的名字查询
    const cptTable = computed(() => {
      return yiMiaoTable.value.filter((item) => {
        return item.name.indexOf(vaccineName.value) > -1
      })
    })
    //点击查询详细的情况
    const clickRow = (val) => {
      newVaccines.value = clone(val)
      chaKanChangJia(val.id).then((res) => {
        changJiaTable.value = clone(res)
      })
    }
    //把对应的厂家放入这里
    const changJiaTable = ref([])

    //疫苗的实体类
    const newVaccines = ref({
      id: '',
      name: '',
      enableFlag: '',
      bookTip: '',
    })

    //疫苗的表单验证规格
    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' },
      ],
    })

    //厂家code的验证
    const code = (rule, value, callback) => {
      let reg = /^\d+$|^\d+[.]?\d+$/
      let items = false
      for (let i = 0; i < changJiaTable.value.length; i++) {
        if (changJiaTable.value[i].code.toString() === value) {
          items = true
          break
        }
      }
      if (items) {
        callback(new Error('编码已存在不要重复添加'))
      } else if (!value) {
        callback(new Error('编码不能为空'))
      } else if (!reg.init(value)) {
        callback(new Error('只能输入数字'))
      } else {
        callback()
      }
    }
    //验证厂家的名字不能一致
    const factoryName = (rule, value, callback) => {
      let items = false
      for (let i = 0; i < changJiaTable.value.length; i++) {
        if (changJiaTable.value[i].name.toString() === value) {
          items = true
          break
        }
      }
      //如果 是修改那么 就不能判断了 一开始就会一样
      if (flag.value === 2) {
        items = false
      }
      if (!value) {
        callback(new Error('不能为空'))
      } else if (items) {
        callback(new Error('厂家名字已存在无法重复添加'))
      } else {
        callback()
      }
    }

    //厂家的表单验证
    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' }],
    })

    //定义变量 用来提交的时候表单验证 也是疫苗的表单中的 ref
    const yiMiaoForm = ref(null)
    //修改疫苗
    const xiuGaiSubmit = async () => {
      const form = unref(yiMiaoForm)
      if (!form) return
      try {
        await form.validate()
        ElMessageBox.confirm('确认修改 <span style="color:teal">' + newVaccines.value.name + '</span>的信息吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true,
        })
          .then(() => {
            xiuGaiYiMiao(newVaccines.value).then((res) => {
              chaKanYiMiao().then((res) => {
                yiMiaoTable.value = res
              })
            })
          })
          .catch(() => {})
      } catch (error) {}
    }
    //厂家实体类
    const covidVaccinateFactory = ref({
      code: null,
      specification: '',
      vaccinateId: 0,
      price: 0,
      name: '',
      enableFlag: '',
    })

    //新增厂家的表单控件名称
    const covidVaccinateFactoryForm = ref(null)

    /**
     * 点击添加厂家的按钮
     * 验证表单 通过了就 添加一条
     * */
    const submitChangJia = async () => {
      covidVaccinateFactory.value.vaccinateId = newVaccines.value.id
      const form = unref(covidVaccinateFactoryForm)
      if (!form) return
      try {
        await form.validate()
        const list = ref([])
        list.value.push(covidVaccinateFactory.value)
        xinZengChangJia(list.value).then((res) => {
          chaKanChangJia(covidVaccinateFactory.value.vaccinateId).then((res) => {
            changJiaTable.value = res
            form.resetFields()
          })
        })
      } catch (error) {}
    }

    /**
     * 修改厂家保存的按钮 触发的事件
     * 修改成功后 要清空表单中的数据
     **/
    const xiuGaiChangJiaBaoCun = async () => {
      const form = unref(covidVaccinateFactoryForm)
      if (!form) return
      try {
        await form.validate()
        xiuGaiChangJia(covidVaccinateFactory.value).then((res) => {
          chaKanChangJia(covidVaccinateFactory.value.vaccinateId).then((res) => {
            changJiaTable.value = res
          })
        })
      } catch (error) {}
    }
    //点击删除厂家
    const shanChuChangJiaSubmit = (val) => {
      shanChuChangJia(val).then((res) => {
        chaKanChangJia(newVaccines.value.id).then((res) => {
          changJiaTable.value = res
        })
      })
    }

    //打开添加或者修改的 抽屉
    const openAddOrModify = ref(false)
    //添加或者修改的抽屉 标题
    const addOrModifyTitle = ref('错误')
    //判断在页面中显示 添加还是修改的按钮
    const flag = ref(0)
    //查看并设置阈值
    const changJiaYuZhiList = ref([])

    /**
     * 点击添加或者修改 一定要写async 不然 await nextTick() 就会报错
     * 因为这里修改和新增 用的是一个form 表单
     * 在用户第一次 点击新增厂家信息的时候是没得问题的
     * 但是，如果用户第一次进入页面的时候就点击修改的话，在点击新增时就会带有上一次点击修改带来的值所以
     * 这个我要再点击的时候，就要重新初始化
     * flag 是用来 判断按钮是修改还是增加的
     * */
    const addOrModify = (val, row) => {
      flag.value = val
      if (val === 1) {
        addOrModifyTitle.value = '新增疫苗【' + newVaccines.value.name + '】的产品信息'
        covidVaccinateFactory.value = {}
        covidVaccinateFactory.value.price = 0
        covidVaccinateFactory.value.enableFlag = 0
        covidVaccinateFactory.value.code = null
      } else if (val === 2) {
        //这里需要克隆 不然数据 会跟着改变
        covidVaccinateFactory.value = clone(row)
        queryChangJiaDuiYingDeYuZhi(covidVaccinateFactory.value.code).then((res) => {
          changJiaYuZhiList.value = res
        })
        addOrModifyTitle.value = '修改该厂家信息'
      }
      openAddOrModify.value = true
    }
    //修改阈值
    const handleChange = (value, scope) => {
      let reg = /^[0-9]+$/
      if (!reg.init(value)) {
        ElMessage({
          type: 'error',
          message: '只能输入整数',
          showClose: true,
          duration: 2500,
        })
        return
      }
      //修改阈值
      let list = [{ id: scope.row.id, value: value }]
      yiJianXiuGaiRiQi(list).then(() => {
        let msg = '提示'
        if (typeof scope.row.name === 'undefined') {
          msg = '日期为：<span style="color:teal">' + scope.row.date + '</span> 阈值修改成功<br>' + '阈值为<span style="color:#E6A23C">【' + value + '】</span>'
        } else {
          msg = '<span style="color:#0081ff">' + scope.row.name + '</span><br>' + '今日阈值修改成功<br>' + '阈值为<span style="color:#E6A23C">【' + value + '】</span>'
        }
        ElNotification({
          message: msg,
          type: 'success',
          title: '成功',
          dangerouslyUseHTMLString: true,
        })
      })
    }
    //点击开启或关闭的开关
    const kaiQiGaiChangJiaYuYueClick = (val) => {
      kaiQiHuoGuanBiYuYue(val.code, val.enableFlag)
    }

    return {
      vaccineName,
      tableHeight,
      yiMiaoTable,
      enableFlagToString,
      cptTable,
      clickRow,
      newVaccines,
      changJiaTable,
      yiMiaoRules,
      xiuGaiSubmit,
      yiMiaoForm,
      covidVaccinateFactory,
      changJiaRules,
      covidVaccinateFactoryForm,
      submitChangJia,
      xiuGaiChangJiaBaoCun,
      shanChuChangJiaSubmit,
      addOrModify,
      openAddOrModify,
      addOrModifyTitle,
      flag,
      changJiaYuZhiList,
      handleChange,
      kaiQiGaiChangJiaYuYueClick,
    }
  },
}
</script>

<style></style>
