<script setup name="fillPurchasingResult">
import { getCurrentInstance, onMounted, ref } from 'vue'
import { changFilesParam, fileFormatVerification, handleFileSuccess, handleFilePreview, fileTypes, fileDesc } from '@/utils/uploadAction.js'
import store from '@/store'
import { useRouter, useRoute } from 'vue-router'
import { submitResult } from '@/http/apis/declareMange/purchaseResults'
import { dictionary } from '@/http/apis/projectCollection/projectCollectionEnter'

const uploadUrl = store.dictStore.uploadUrl,
  { proxy } = getCurrentInstance(),
  router = useRouter(),
  route = useRoute()
const formRef = ref(),
  // 手机号码校验
  checkTelPhone = (rule, value, callback) => {
    if (value === '') {
      return callback(new Error('请输入正确的手机号'))
    } else {
      const regIdCard =
            /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regIdCard.test(value)) {
        callback()
      } else {
        return callback(new Error('请输入正确的手机号'))
      }
    }
  },
  rules = {
    bidName: [{ required: true, message: '请输入标段名称' }],
    supplier: [{ required: true, message: '请输入供应商' }],
    supplierContact: [{ required: true, message: '请输入供应商联系人' }],
    supplierContactInfo: [
      { required: true, message: '请输入供应商联系方式' },
      { validator: checkTelPhone, trigger: 'blur' }
    ],
    purchaseMethod: [{ required: true, message: '请选择采购方式' }],
    transactionAmount: [{ required: true, message: '请输入成交金额' }],
    transactionTime: [{ required: true, message: '请选择成交时间' }],
    biddingDoc: [{ required: true, message: '请上传投标文件' }],
    bidDoc: [{ required: true, message: '请上传招标文件' }],
    acceptanceLetter: [{ required: true, message: '请上传中标通知书' }]
  },
  formData = ref({
    sections: [{
      biddingDoc: [],
      bidDoc: [],
      acceptanceLetter: []
    }]
  }),
  submitLoading = ref(false),
  submit = async (formEl) => {
    if (!formEl) {
      return
    }
    formEl.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        const postData = {
          projectId: route.query.id,
          tenders: formData.value.sections.map(i => {
            return {
              ...i,
              biddingDoc: i.biddingDoc && JSON.stringify(changFilesParam(i.biddingDoc)),
              bidDoc: i.bidDoc && JSON.stringify(changFilesParam(i.bidDoc)),
              acceptanceLetter: i.acceptanceLetter && JSON.stringify(changFilesParam(i.acceptanceLetter))
            }
          })
        }
        try {
          await submitResult(postData)
          submitLoading.value = false
          proxy.$message.success('提交成功')
          router.go(-1)
        } catch (e) {
          submitLoading.value = false
        }
      }
    })
  },
  // 添加标段
  add = () => {
    if (formData.value.sections?.length >= 10) {
      proxy.$message.warning('最多添加10个标段')
      return
    }
    formData.value.sections.push({
      biddingDoc: [],
      bidDoc: [],
      acceptanceLetter: []
    })
  },
  // 删除标段
  del = (index) => {
    formData.value.sections.splice(index, 1)
  },
  dictionaryList = ref([])
onMounted(async () => {
  dictionaryList.value = (await dictionary()).data
})
</script>
<template>
  <div class="fillPurchasingResult footerPage">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-position="right"
      label-width="180px"
      label-suffix=":"
      scroll-to-error
    >
      <el-card v-for="(item,index) in formData.sections" :key="index" class="w-full mb-16">
        <template #header>
          <div class="flex justify-between">
            <span>标段{{ index+1 }}</span>
            <el-button
              v-if="formData.sections?.length>1"
              link
              type="danger"
              @click="del(index)"
            >删除</el-button>
          </div>
        </template>
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="标段名称" :prop="`sections[${index}].bidName`" :rules="[{ required: true, message: '请输入' }]">
              <el-input v-model="formData.sections[index].bidName" maxlength="50" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" :prop="`sections[${index}].supplier`" :rules="[{ required: true, message: '请输入' }]">
              <el-input v-model="formData.sections[index].supplier" maxlength="50" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商统一社会信用代码" :prop="`sections[${index}].supplierSocialCreditCode`" :rules="[{ required: true, message: '请输入' }]">
              <el-input v-model="formData.sections[index].supplierSocialCreditCode" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商联系人" :prop="`sections[${index}].supplierContact`" :rules="[{ required: true, message: '请输入' }]">
              <el-input v-model="formData.sections[index].supplierContact" maxlength="50" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商联系方式" :prop="`sections[${index}].supplierContactInfo`" :rules="[{ required: true, message: '请输入' }]">
              <el-input v-model="formData.sections[index].supplierContactInfo" maxlength="11" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="采购方式" :prop="`sections[${index}].purchaseMethod`" :rules="[{ required: true, message: '请选择' }]">
              <el-radio-group v-model="formData.sections[index].purchaseMethod">
                <el-radio
                  v-for="(row,key) in dictionaryList?.filter(i => i.type === 'PURCHASE_METHOD')"
                  :key="key"
                  :label="row.value"
                >{{ row.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成交金额" :prop="`sections[${index}].transactionAmount`" :rules="[{ required: true, message: '请输入' }]">
              <el-input-number
                v-model="formData.sections[index].transactionAmount"
                placeholder="请填写"
                :min="0"
                :controls="false"
                @mousewheel.prevent
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="成交时间"
              :prop="`sections[${index}].transactionTime`"
              :rules="[{ required: true, message: '请选择' }]"
            >
              <el-date-picker
                v-model="formData.sections[index].transactionTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item v-if="['00','05'].includes(formData.sections[index].purchaseMethod)" label="采购代理机构">
              <el-input v-model="formData.sections[index].agency" maxlength="50" placeholder="请输入" />
            </el-form-item>
            <el-form-item
              v-else
              label="采购代理机构"
              :prop="`sections[${index}].agency`"
              :rules="[{ required: true, message: '请输入' }]"
            >
              <el-input v-model="formData.sections[index].agency" maxlength="50" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="['00','05'].includes(formData.sections[index].purchaseMethod)" label="采购代理机构统一社会信用代码">
              <el-input v-model="formData.sections[index].purchaseSocialCreditCode" placeholder="请输入" />
            </el-form-item>
            <el-form-item
              v-else
              label="采购代理机构统一社会信用代码"
              :prop="`sections[${index}].purchaseSocialCreditCode`"
              :rules="[{ required: true, message: '请输入' }]"
            >
              <el-input v-model="formData.sections[index].purchaseSocialCreditCode" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预算执行确认书编号">
              <el-input v-model="formData.sections[index].budgetExecConfirmNo" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="投标文件"
              :prop="`sections[${index}].biddingDoc`"
              :rules="[{ required: true, message: '请上传' }]"
            >
              <el-upload
                v-model:file-list="formData.sections[index].biddingDoc"
                class="w-full"
                :action="uploadUrl"
                :on-success="res => handleFileSuccess(res, formData.sections[index].biddingDoc)"
                :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
                :accept="fileTypes.map(i=>`.${i}`).join(',')"
                :on-preview="handleFilePreview"
              >
                <el-button type="primary" plain>选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持{{ fileDesc }}文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="formData.sections[index].purchaseMethod!=='00'"
              label="招标文件"
              :prop="`sections[${index}].bidDoc`"
              :rules="[{ required: true, message: '请上传' }]"
            >
              <el-upload
                v-model:file-list="formData.sections[index].bidDoc"
                class="w-full"
                :action="uploadUrl"
                :on-success="res => handleFileSuccess(res, formData.sections[index].bidDoc)"
                :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
                :accept="fileTypes.map(i=>`.${i}`).join(',')"
                :on-preview="handleFilePreview"
              >
                <el-button type="primary" plain>选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持{{ fileDesc }}文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item
              v-else
              label="招标文件"
            >
              <el-upload
                v-model:file-list="formData.sections[index].bidDoc"
                class="w-full"
                :action="uploadUrl"
                :on-success="res => handleFileSuccess(res, formData.sections[index].bidDoc)"
                :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
                :accept="fileTypes.map(i=>`.${i}`).join(',')"
                :on-preview="handleFilePreview"
              >
                <el-button type="primary" plain>选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持{{ fileDesc }}文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="!['00','05'].includes(formData.sections[index].purchaseMethod)"
              label="中标通知书"
              :prop="`sections[${index}].acceptanceLetter`"
              :rules="[{ required: true, message: '请上传' }]"
            >
              <el-upload
                v-model:file-list="formData.sections[index].acceptanceLetter"
                class="w-full"
                :action="uploadUrl"
                :on-success="res => handleFileSuccess(res, formData.sections[index].acceptanceLetter)"
                :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
                :accept="fileTypes.map(i=>`.${i}`).join(',')"
                :on-preview="handleFilePreview"
              >
                <el-button type="primary" plain>选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持{{ fileDesc }}文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item
              v-else
              label="中标通知书"
            >
              <el-upload
                v-model:file-list="formData.sections[index].acceptanceLetter"
                class="w-full"
                :action="uploadUrl"
                :on-success="res => handleFileSuccess(res, formData.sections[index].acceptanceLetter)"
                :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
                :accept="fileTypes.map(i=>`.${i}`).join(',')"
                :on-preview="handleFilePreview"
              >
                <el-button type="primary" plain>选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持{{ fileDesc }}文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <p>
        <el-button
          type="primary"
          plain
          icon="Plus"
          class="w-full"
          @click="add"
        >添加标段</el-button>
      </p>
    </el-form>
    <div class="footer">
      <el-button @click="router.go(-1)"> 返回 </el-button>
      <el-button type="primary" :loading="submitLoading" @click="submit(formRef)"> 提交 </el-button>
    </div>
  </div>
</template>
