<template>
  <div class="application-dialog-container">
    <el-dialog
      :title="state.dialog.title"
      @close="onCancel"
      :close-on-click-modal="false"
      v-model="state.dialog.isShowDialog"
      width="100%"
    >
      <el-form
        ref="expertDialogFormRef"
        :model="state.form"
        :rules="rules"
        size="default"
        label-width="140px"
        label-position="top"
      >
        <h4 class="mb8 mt8">基本信息</h4>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="课题名称"
              prop="projectGroupId"
            >
              <el-select
                v-model="state.form.projectGroupId"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in projects"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="姓名"
              prop="group"
            >
              <el-input
                v-model="userInfos.userName"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <h4 class="mb8 mt10">实验动物笼位预约信息</h4>
        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="12">
            <el-form-item
              label="笼位数量"
              prop="number"
            >
              <el-input-number
                v-model="state.form.number"
                style="width: 100%"
                :min="1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="选择时间"
              prop="startDate"
            >
              <el-date-picker
                v-model="state.form.startDate"
                type="date"
                placeholder="请选择时间"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="12">
            <el-form-item
              label="品种品系"
              prop="categoryId"
            >
              <el-select
                v-model="state.form.categoryId"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in animalTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="级别"
              prop="level"
            >
              <el-select
                v-model="state.form.level"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in LeavelList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="12">
            <el-form-item
              label="雄性"
              prop="maleNumber"
            >
              <el-input-number
                style="width: 100%"
                placeholder="雄性数量"
                v-model="state.form.maleNumber"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="雌性"
              prop="famaleNumber"
            >
              <el-input-number
                style="width: 100%"
                placeholder="雌性数量"
                v-model="state.form.famaleNumber"
                :min="0"
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="24">
            <el-form-item
              label="数量(雄性+雌性)"
              prop="maleNumber"
            >
              <div style="width: 100%; display: flex; justify-content: space-between">
                <el-input-number
                  placeholder="雄性数量"
                  v-model="state.form.maleNumber"
                  :min="0"
                />
                +
                <el-input-number
                  placeholder="雌性数量"
                  v-model="state.form.famaleNumber"
                  :min="0"
                />
              </div>
              <div style="width: 100%; margin-top: 10px">
                <el-input
                  placeholder="总数"
                  v-model="animalNumber"
                />
              </div>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item
              label="体重"
              prop="weight"
            >
              <el-input-number
                v-model="state.form.weight"
                style="width: 100%"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item
              label="周龄"
              prop="age"
            >
              <el-input-number
                v-model="state.form.age"
                style="width: 100%"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item
              label="饲养总天数"
              prop="feedingDay"
            >
              <el-input-number
                v-model="state.form.feedingDay"
                style="width: 100%"
                :min="1"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <h4 class="mb8 mt20">采购渠道</h4>
        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item
              label="采购渠道"
              prop="buyFrom"
            >
              <el-radio-group v-model="state.form.buyFrom">
                <el-radio
                  :label="ProcurementChannels.PURCHASED_BY_OTHERS"
                  size="large"
                >
                  动物房代购
                </el-radio>
                <el-radio
                  :label="ProcurementChannels.PURCHASED_BY_MYSELF"
                  size="large"
                >
                  自行购买
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          v-if="state.form.buyFrom === ProcurementChannels.PURCHASED_BY_MYSELF"
          class="mt10"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item
              label="外购来源单位"
              prop="comeFromUnit"
            >
              <el-input v-model="state.form.comeFromUnit" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item
              label="动物到达时间"
              prop="comeTime"
            >
              <el-date-picker
                v-model="state.form.comeTime"
                type="date"
                placeholder="请选择到达时间"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
          v-if="state.form.buyFrom === ProcurementChannels.PURCHASED_BY_MYSELF"
        >
          <el-col :span="24">
            <el-form-item
              label="生产许可证副本"
              prop="licenseNumberFile"
              :rules="{ required: state.form.buyFrom === ProcurementChannels.PURCHASED_BY_MYSELF, message: '不能为空', trigger: 'change' }"
            >
              <el-upload
                v-model:file-list="licenseNumberFileList"
                class="upload-demo"
                :action="uploadUrl"
                :limit="1"
                style="width: 100%"
                :before-upload="beforeAvatarFileUpload"
                :on-remove="() => handleRemove(UploadFileType.LICENSE_NUMBER)"
                :on-success="(res: any, file: UploadFile) => handleSuccess(res, UploadFileType.LICENSE_NUMBER, file)"
              >
                <el-button type="primary">点击上传</el-button>
                <div class="el-upload__tip ml10">支持格式:jpg png pdf等,单个文件不超过20MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
          v-if="state.form.buyFrom === ProcurementChannels.PURCHASED_BY_MYSELF"
        >
          <el-col :span="24">
            <el-form-item
              label="近三个月动物质量检测证明"
              prop="animalTestDateFile"
              :rules="{ required: state.form.buyFrom === ProcurementChannels.PURCHASED_BY_MYSELF, message: '不能为空', trigger: 'change' }"
            >
              <el-upload
                v-model:file-list="animalTestDateFileList"
                class="upload-demo"
                :action="uploadUrl"
                :limit="1"
                style="width: 100%"
                :before-upload="beforeAvatarFileUpload"
                :on-remove="() => handleRemove(UploadFileType.ANIMAL_TEST_DATE)"
                :on-success="(res: any, file: UploadFile) => handleSuccess(res, UploadFileType.ANIMAL_TEST_DATE, file)"
              >
                <el-button type="primary">点击上传</el-button>
                <div class="el-upload__tip ml10">支持格式:jpg png pdf等,单个文件不超过20MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
          v-if="state.form.buyFrom === ProcurementChannels.PURCHASED_BY_MYSELF"
        >
          <el-col :span="24">
            <el-form-item
              label="基因鉴定报告"
              prop="geneIdentificationFile"
            >
              <el-upload
                v-model:file-list="geneIdentificationFileList"
                class="upload-demo"
                :action="uploadUrl"
                :limit="1"
                style="width: 100%"
                :before-upload="beforeAvatarFileUpload"
                :on-remove="() => handleRemove(UploadFileType.ENV_TEST_DATE)"
                :on-success="(res: any, file: UploadFile) => handleSuccess(res, UploadFileType.ENV_TEST_DATE, file)"
              >
                <el-button type="primary">点击上传</el-button>
                <div class="el-upload__tip ml10">支持格式:jpg png pdf等,单个文件不超过20MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <h4 class="mb8 mt20">特殊要求和附件</h4>
        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item
              label="是否有特殊饲养要求"
              prop="hasFeedingSpecial"
            >
              <el-radio-group v-model="state.form.hasFeedingSpecial">
                <el-radio
                  :label="FeedingSpecial.HAVE_FEEDING_SPECIAL"
                  size="large"
                >
                  有
                </el-radio>
                <el-radio
                  :label="FeedingSpecial.NO_FEEDING_SPECIAL"
                  size="large"
                >
                  无
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col
            :span="24"
            v-if="state.form.hasFeedingSpecial === FeedingSpecial.HAVE_FEEDING_SPECIAL"
          >
            <el-form-item
              label="特殊饲养要求"
              prop="feedingSpecialDesc"
            >
              <el-input
                placeholder="输入特殊饲养要求，如每天更换垫料等"
                v-model="state.form.feedingSpecialDesc"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item
              label="笼位预约表"
              prop="cageAppointFile"
            >
              <el-upload
                v-model:file-list="cageAppointFileList"
                class="upload-demo"
                :action="uploadUrl"
                :limit="1"
                style="width: 100%"
                :before-upload="beforeAvatarFileUpload"
                :on-remove="() => handleRemove(UploadFileType.CAGE_APPOINT_FILE)"
                :on-success="(res: any, file: UploadFile) => handleSuccess(res, UploadFileType.CAGE_APPOINT_FILE, file)"
              >
                <el-button type="primary">点击上传</el-button>
                <div class="el-upload__tip ml10">支持格式:jpg png pdf等,单个文件不超过20MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row> -->

        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item
              label="实验动物福利伦理审查申请表"
              prop="ethicsCheckFile"
            >
              <el-upload
                v-model:file-list="ethicsCheckFileList"
                class="upload-demo"
                :action="uploadUrl"
                :limit="1"
                style="width: 100%"
                :before-upload="beforeAvatarFileUpload"
                :on-remove="() => handleRemove(UploadFileType.ETHICS_CHECK_FILE)"
                :on-success="(res: any, file: UploadFile) => handleSuccess(res, UploadFileType.ETHICS_CHECK_FILE, file)"
              >
                <el-button type="primary">点击上传</el-button>
                <div class="el-upload__tip ml10">支持格式:jpg png pdf等,单个文件不超过20MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          class="mt10"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item
              label="实验动物福利伦理审查意见表"
              prop="ethicsAdviceFile"
            >
              <el-upload
                v-model:file-list="ethicsAdviceFileList"
                class="upload-demo"
                :action="uploadUrl"
                :limit="1"
                style="width: 100%"
                :before-upload="beforeAvatarFileUpload"
                :on-remove="() => handleRemove(UploadFileType.ETHICS_ADVICE_FILE)"
                :on-success="(res: any, file: UploadFile) => handleSuccess(res, UploadFileType.ETHICS_ADVICE_FILE, file)"
              >
                <el-button type="primary">点击上传</el-button>
                <div class="el-upload__tip ml10">支持格式:jpg png pdf等,单个文件不超过20MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-checkbox
          style="margin-top: 30px; margin-bottom: 30px"
          v-model="safePromise"
        >
          <div class="safePromise">
            本人（以上所述课题的负责人）谨此声明：本项目所包含的实验动物、实验方法、实验材料及试剂无放射性、感染性和化学毒性，所有参与实验人员在实验过程中自愿遵守遵义医科大学附属医院实验动物房的管理制度和操作流程，愿意根据其规定的付费方式向遵义医科大学附属医院实验动物房支付所有的费用。
          </div>
        </el-checkbox>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button
            type="info"
            @click="onCancel"
            size="default"
          >
            取 消
          </el-button>
          <el-button
            color="#2c78ff"
            @click="onSubmit()"
            size="default"
          >
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemProDialog">
  import { reactive, ref, computed } from 'vue'
  import to from 'await-to-js'
  import { ElMessage } from 'element-plus'
  import { UploadFile } from 'element-plus/es/components'
  import dayjs from 'dayjs'
  import { storeToRefs } from 'pinia'
  import { usePlatAnimalCageApplicationApi } from '/@/api/platform/animal'
  import { LeavelList } from '/@/constants/pageConstants'
  import { deepClone } from '/@/utils/other'
  import { useUserInfo } from '/@/stores/userInfo'
  import { ProcurementChannels, FeedingSpecial, UploadFileType } from '/@/constants/pageConstants'

  const uploadUrl = (import.meta as any).env.VITE_UPLOAD

  const stores = useUserInfo()
  const { userInfos } = storeToRefs(stores)

  // 定义子组件向父组件传值/事件
  const emit = defineEmits(['refresh'])

  const platAnimalCageApplicationApi = usePlatAnimalCageApplicationApi()

  const expertDialogFormRef = ref()
  const projectGroupList = ref<any[]>([])
  const projects = ref<any[]>([])

  const rules = {
    projectGroupId: { required: true, message: '不能为空', trigger: 'change' },
    categoryId: { required: true, message: '不能为空', trigger: 'change' },
    number: { required: true, message: '不能为空', trigger: 'change' },
    startDate: { required: true, message: '不能为空', trigger: 'change' },
    // maleNumber: { required: true, message: '不能为空', trigger: 'change' },
    // weight: { required: true, message: '不能为空', trigger: 'change' },
    buyFrom: { required: true, message: '不能为空', trigger: 'change' },
    feedingDay: { required: true, message: '不能为空', trigger: 'change' },
    comeFromUnit: { required: true, message: '不能为空', trigger: 'change' },
    feedingSpecialDesc: { required: true, message: '不能为空', trigger: 'change' },
    ethicsCheckFile: { required: true, message: '不能为空', trigger: 'change' },
    ethicsAdviceFile: { required: true, message: '不能为空', trigger: 'change' },
  }

  // const animalNumber = computed(() => {
  //   const maleNumber = state.form.maleNumber || 0
  //   const famaleNumber = state.form.famaleNumber || 0
  //   return maleNumber + famaleNumber
  // })

  const licenseNumberFileList = ref<UploadFile[]>([])
  const animalTestDateFileList = ref<UploadFile[]>([])
  const geneIdentificationFileList = ref<UploadFile[]>([])
  const cageAppointFileList = ref<UploadFile[]>([])
  const ethicsCheckFileList = ref<UploadFile[]>([])
  const ethicsAdviceFileList = ref<UploadFile[]>([])

  const safePromise = ref<boolean>(false)
  const animalTypeList = ref<any[]>([])
  const state = reactive({
    form: {
      projectGroupName: '',
      projectGroupId: null,
      categoryName: '',
      categoryId: null,
      level: null,
      number: 1,
      startDate: '',
      maleNumber: 0,
      famaleNumber: 0,
      weight: 0,
      age: 0,
      feedingDay: 0,
      buyFrom: ProcurementChannels.PURCHASED_BY_OTHERS,
      comeTime: '',
      comeFromUnit: '',
      licenseNumberFile: [],
      animalTestDateFile: [],
      geneIdentificationFile: [],
      hasFeedingSpecial: FeedingSpecial.HAVE_FEEDING_SPECIAL,
      feedingSpecialDesc: '',
      cageAppointFile: [],
      ethicsCheckFile: [],
      ethicsAdviceFile: [],
    },
    safePromise: false,
    safeRead: false,
    dialog: {
      isShowDialog: false,
      type: '',
      title: '',
      submitTxt: '',
    },
  })

  const getDicts = () => {
    Promise.all([
      platAnimalCageApplicationApi.getAnimalTypeList({}),
      platAnimalCageApplicationApi.getProjectGroup({}),
    ]).then(([animalType, projectGroup]) => {
      animalTypeList.value = animalType.data
      if (projectGroup && projectGroup.data) {
        projectGroupList.value = projectGroup.data
        const currentProject = projectGroup.data[0]?.projects
        if (currentProject) {
          projects.value = currentProject
        }
      }
    })
  }
  // 打开弹窗
  const openDialog = async (type: 'add' | 'edit') => {
    getDicts()
    state.dialog.type = type
    state.dialog.isShowDialog = true
  }

  // 关闭弹窗
  const closeDialog = () => {
    expertDialogFormRef.value.resetFields()
    state.dialog.isShowDialog = false
  }
  // 取消
  const onCancel = () => {
    closeDialog()
  }

  const beforeAvatarFileUpload = (file: { size: number }) => {
    let isLt10m = file.size / 1024 / 1024 / 20 < 1
    if (!isLt10m) {
      ElMessage.error('上传文件大小不能超过 20MB!')
      return false
    }
    return true
  }

  const handleRemove = (type: UploadFileType) => {
    if (type === UploadFileType.LICENSE_NUMBER) {
      licenseNumberFileList.value = []
      state.form.licenseNumberFile = []
    } else if (type === UploadFileType.ANIMAL_TEST_DATE) {
      animalTestDateFileList.value = []
      state.form.animalTestDateFile = []
    } else if (type === UploadFileType.ENV_TEST_DATE) {
      geneIdentificationFileList.value = []
      state.form.geneIdentificationFile = []
    } else if (type === UploadFileType.CAGE_APPOINT_FILE) {
      cageAppointFileList.value = []
      state.form.cageAppointFile = []
    } else if (type === UploadFileType.ETHICS_CHECK_FILE) {
      ethicsCheckFileList.value = []
      state.form.ethicsCheckFile = []
    } else if (type === UploadFileType.ETHICS_ADVICE_FILE) {
      ethicsAdviceFileList.value = []
      state.form.ethicsAdviceFile = []
    }
  }

  const handleSuccess = (res: { Data: string }, type: UploadFileType, file: UploadFile) => {
    console.log('ressss', res, file)
    if (type === UploadFileType.LICENSE_NUMBER) {
      state.form.licenseNumberFile = [{ name: file.name, url: res?.Data }]
    } else if (type === UploadFileType.ANIMAL_TEST_DATE) {
      state.form.animalTestDateFile = [{ name: file.name, url: res?.Data }]
    } else if (type === UploadFileType.ENV_TEST_DATE) {
      state.form.geneIdentificationFile = [{ name: file.name, url: res?.Data }]
    } else if (type === UploadFileType.CAGE_APPOINT_FILE) {
      state.form.cageAppointFile = [{ name: file.name, url: res?.Data }]
    } else if (type === UploadFileType.ETHICS_CHECK_FILE) {
      state.form.ethicsCheckFile = [{ name: file.name, url: res?.Data }]
    } else if (type === UploadFileType.ETHICS_ADVICE_FILE) {
      state.form.ethicsAdviceFile = [{ name: file.name, url: res?.Data }]
    }
  }

  // 提交
  const onSubmit = async () => {
    expertDialogFormRef.value.validate(async (valid: boolean) => {
      if (!valid) return

      if (!safePromise.value) {
        ElMessage.error('请阅读并勾选安全承诺！')
        return
      }

      if (!state.form.maleNumber && !state.form.famaleNumber) {
        ElMessage.error('请输入雄性或雌性数量！')
        return
      }

      const params = {
        ...deepClone(state.form),
        categoryName: animalTypeList.value.find((item) => item.id == state.form.categoryId)?.name,
        projectGroupName: projects.value.find((item) => item.id == state.form.projectGroupId)?.projectName,
        startDate: dayjs(state.form.startDate).format('YYYY-MM-DD'),
        comeTime: state.form.comeTime ? dayjs(state.form.comeTime).format('YYYY-MM-DD') : '',
        licenseNumberFile: JSON.stringify(state.form.licenseNumberFile),
        animalTestDateFile: JSON.stringify(state.form.animalTestDateFile),
        geneIdentificationFile: JSON.stringify(state.form.geneIdentificationFile),
        cageAppointFile: JSON.stringify(state.form.cageAppointFile),
        ethicsCheckFile: JSON.stringify(state.form.ethicsCheckFile),
        ethicsAdviceFile: JSON.stringify(state.form.ethicsAdviceFile),
      }

      Object.entries(params).forEach(([key, value]) => {
        if (value === '' || value === null) {
          delete params[key as keyof typeof params]
        }
      })

      const post = platAnimalCageApplicationApi.create
      const [err]: ToResponse = await to(post(params))
      if (err) return
      ElMessage.success('操作成功')
      closeDialog()
      emit('refresh')
    })
  }

  // 暴露变量
  defineExpose({
    openDialog,
  })
</script>
<style lang="scss" scoped>
  .application-dialog-container {
    .el-select {
      width: 100%;
    }
    .el-dialog {
      max-height: 80%;
      overflow: auto;
    }
    .safePromise {
      white-space: pre-wrap;
    }
  }
  h4 {
    font-size: 18px;
  }
  ul {
    padding-left: 20px;
  }
  .text {
    p {
      text-indent: 2em;
    }
  }
  .el-upload + .el-button {
    vertical-align: top;
  }
</style>
