<!-- 供方名录 可编辑基本信息 -->
<script name="SupplierInfoBasicForEdit" lang="ts" setup>
import type { UploadProps } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IDictType, ISupplierInfo } from './supplier-interface'
import { mailboxValidator, phoneValidator, postalCodeValidator, websiteValidator } from './supplier-interface'
import { UploadFile } from '@/api/file'
import { failUpdateSupplierBasic, saveSupplierBasic, submitSupplierBasic, updateSupplierBasic } from '@/api/resource/supplier'

const props = defineProps({
  operation: { type: String, default: '' },
})

const emit = defineEmits(['afterSaveDraft', 'commitSuccess'])

// 关键字段是否可以编辑
const keyFieldsDisable = ref<boolean>(true)

// 供方类型字典值
const supplierTypeDictInChild = ref<Array<IDictType>>([])

const supplierInfo = ref<ISupplierInfo>({
  id: '',
  supplierNo: '',
  supplierName: '',
  briefName: '',
  supplierType: '',
  supplierTypeName: '',
  taxNumber: '',
  bankAccount: '',
  bankName: '',
  bankAccountNumber: '',
  director: '',
  phone: '',
  postalCode: '',
  fax: '',
  mailbox: '',
  website: '',
  companyAddress: '',
  supplierContent: '',
  minioFileName: '',
  remark: '',
  approvalStatus: '',
  approvalStatusName: '',
  processId: '',
  taskId: '',
  createUserName: '',
  createTime: '',
})

const basicFormRef = ref()

const supplierBasicRules = ref({
  supplierName: [{ required: true, message: '供方名称不能为空', trigger: 'blur' }],
  supplierType: [{ required: true, message: '供方类型不能为空，请选择', trigger: ['change', 'blur'] }],
  supplierContent: [{ required: true, message: '服务和供应内容不能为空', trigger: 'blur' }],
  phone: [{ message: '请输入符合规范的手机号码', trigger: 'blur', validator: phoneValidator }],
  postalCode: [{ message: '邮政编码为6位数字', trigger: 'blur', validator: postalCodeValidator }],
  companyAddress: [{ required: true, message: '地址不能为空', trigger: 'blur' }],
  mailbox: [{ message: '请输入规范的邮箱', trigger: 'blur', validator: mailboxValidator }],
  website: [{ message: '请输入规范的网址', trigger: 'blur', validator: websiteValidator }],
}) // 表单验证规则

// 逻辑
// 查询人员基本信息 从缓存中直接取
const getSupplierBasicInCache = () => {
  supplierInfo.value = JSON.parse(sessionStorage.getItem('supplierInfo')!)
}

// 设置字段是否可以编辑
const setFieldsDisable = (editable: boolean) => {
  keyFieldsDisable.value = editable
}

// 保存至草稿箱
const addSupplierBase = () => {
  saveSupplierBasic(supplierInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      // 设置返回的供方id和供方编号
      supplierInfo.value.supplierNo = res.data.supplierNo
      supplierInfo.value.id = res.data.id
      // 返回保存后生成的id
      emit('afterSaveDraft', res.data.id)
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}
// 编辑草稿箱（不走流程审批）
const updateSupplierBase = () => {
  updateSupplierBasic(supplierInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 保存基本信息
const saveBasicForm = async () => {
  if (!basicFormRef) { return }

  await basicFormRef.value.validate((valid: boolean, fields: any) => {
    if (valid === true) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (props.operation === 'create') {
          addSupplierBase()
        }
        else if (props.operation === 'update') {
          updateSupplierBase()
        }
      })
    }
  })
}

// 提交供方审批
const submitBasicForm = async () => {
  ElMessageBox.confirm(`是否提交审批单 ${supplierInfo.value.supplierNo}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    submitSupplierBasic({
      formId: 'zyglhggfml',
      id: supplierInfo.value.id,
    }).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`审批单 ${supplierInfo.value.supplierNo} 提交成功`)
        emit('commitSuccess', supplierInfo.value)
      }
      else {
        ElMessage.error(`审批单 ${supplierInfo.value.supplierNo} 提交失败：${res.message}`)
      }
    })
  })
}

// 保存并提交审批单 重新进入流程审批
const failUpdateSubmitBasicForm = async () => {
  if (!basicFormRef) { return }
  await basicFormRef.value.validate((valid: boolean) => {
    if (valid === true) {
      failUpdateSupplierBasic(supplierInfo.value).then((res) => {
        if (res.code === 200) {
          // 提示保存成功
          ElMessage.success(`审批单 ${supplierInfo.value.supplierNo} 提交成功`)
          emit('commitSuccess', supplierInfo.value)
        }
        else {
          // 提示失败信息
          ElMessage.error(`审批单 ${supplierInfo.value.supplierNo} 提交失败：${res.message}`)
        }
      })
    }
  })
}

// 上传请求
const uploadQuarterlyEvaluateFile: any = (file: any) => {
  const fd = new FormData()
  fd.append('multipartFile', file.file)
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  UploadFile(fd).then((res) => {
    if (res.code === 200) {
      ElMessage.success('上传成功')
      supplierInfo.value.minioFileName = res.data[0]
      loading.close()
    }
  }).catch(() => {
    loading.close()
    ElMessage.error('上传失败')
  })
}

// 上传之前的验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg') {
    ElMessage.error('只能上传png/jpeg/jpg格式的图片')
    return false
  }
  else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能大于2MB')
    return false
  }
  return true
}

// 监听 显示中文 立即监听
watch(() => supplierInfo.value.supplierType, (newVal) => {
  if (supplierTypeDictInChild.value.length === 0) {
    supplierTypeDictInChild.value = JSON.parse(sessionStorage.getItem('bizSupplierType')!)
  }
  const targetList = supplierTypeDictInChild.value.filter(item => item.value === newVal)
  if (targetList.length > 0) {
    supplierInfo.value.supplierTypeName = targetList[0].name
  }
  else {
    supplierInfo.value.supplierTypeName = ''
  }
}, { immediate: true })

defineExpose({
  getSupplierBasicInCache,
  setFieldsDisable,
  saveBasicForm,
  submitBasicForm,
  failUpdateSubmitBasicForm,
})
</script>

<template>
  <app-container>
    <el-form ref="basicFormRef" :model="supplierInfo" :rules="supplierBasicRules" label-position="right" label-width="110" border stripe>
      <el-row :gutter="24">
        <!-- 第一行 第一列 -->
        <el-col :span="6">
          <el-form-item label="供方编号">
            <el-input v-model="supplierInfo.supplierNo" placeholder="供方编号，保存后自动生成" :readonly="true" :disabled="true" />
          </el-form-item>
          <el-form-item label="税号">
            <el-input v-model="supplierInfo.taxNumber" :clearable="true" placeholder="请输入税号" />
          </el-form-item>
          <el-form-item label="邮编" prop="postalCode">
            <el-input v-model="supplierInfo.postalCode" placeholder="请输入邮政编码" :clearable="true" />
          </el-form-item>
          <el-form-item label="邮箱" prop="mailbox">
            <el-input v-model="supplierInfo.mailbox" placeholder="请输入邮箱" :clearable="true" />
          </el-form-item>
        </el-col>

        <!-- 第一行 第二列 -->
        <el-col :span="6">
          <el-form-item label="供方名称" prop="supplierName">
            <el-input v-model="supplierInfo.supplierName" :clearable="true" placeholder="请输入供方名称" :disabled="keyFieldsDisable" />
          </el-form-item>
          <el-form-item label="银行账户名">
            <el-input v-model="supplierInfo.bankAccount" :clearable="true" placeholder="请输入银行账户名" />
          </el-form-item>
          <el-form-item label="联系人">
            <el-input v-model="supplierInfo.director" :clearable="true" placeholder="请输入联系人" />
          </el-form-item>
          <el-form-item label="网址" prop="website">
            <el-input v-model="supplierInfo.website" :clearable="true" placeholder="请输入网址， http://或http://" />
          </el-form-item>
        </el-col>

        <!-- 第一行 第三列 -->
        <el-col :span="6">
          <el-form-item label="供方简称">
            <el-input v-model="supplierInfo.briefName" :clearable="true" placeholder="请输入供方简称" />
          </el-form-item>
          <el-form-item label="银行名称">
            <el-input v-model="supplierInfo.bankName" :clearable="true" placeholder="请输入银行名称" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="supplierInfo.phone" :clearable="true" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>

        <!-- 第一行 第四列 -->
        <el-col :span="6">
          <el-form-item label="供方类型" prop="supplierType">
            <el-select v-model="supplierInfo.supplierType" placeholder="请选择供方类型" style="width: 100%;" :clearable="true">
              <el-option v-for="dict in supplierTypeDictInChild" :key="dict.id" :label="dict.name" :value="dict.value" />
            </el-select>
            <el-input v-model="supplierInfo.supplierTypeName" type="hidden" />
          </el-form-item>
          <el-form-item label="银行账号">
            <el-input v-model="supplierInfo.bankAccount" :clearable="true" placeholder="请输入银行账号" />
          </el-form-item>
          <el-form-item label="传真" prop="fax">
            <el-input v-model="supplierInfo.fax" :clearable="true" placeholder="请输入传真" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="24">
        <!-- 第一列 -->
        <el-col :span="12">
          <el-form-item label="地址" prop="companyAddress">
            <el-input v-model="supplierInfo.companyAddress" placeholder="请输入地址" :clearable="true" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="服务和供应的内容" prop="supplierContent">
            <el-input v-model="supplierInfo.supplierContent" type="textarea" :rows="2" :clearable="true" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model="supplierInfo.remark" placeholder="请输入备注信息" type="textarea" :clearable="true" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="附件">
            <el-upload
              :http-request="uploadQuarterlyEvaluateFile"
              :before-upload="beforeAvatarUpload"
              accept="image/png, image/jpeg,image/jpg"
            >
              <el-button type="primary">
                上传
              </el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </app-container>
</template>
