<script lang="ts" setup name="manageAdd">
/**
 * 添加/编辑/详情溯源供方
 */
import type { Ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadUserFile } from 'element-plus'
import type { ISupplier } from '../checkList_interface'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { UploadFile } from '@/api/measure/file'
import { getSoucreListDetail, getSoucreListlevelType, sourceSave, sourceSubmit } from '@/api/measure/source'
import { getAddCheckInfo, getselectCheckInfo } from '@/api/device/checkList'
import { validatePhone } from '@/utils/validate'
import { SCHEDULE } from '@/utils/scheduleDict'
import type { IAddress } from '@/components/AddressSelect/address-interface'
import useUserStore from '@/store/modules/user'
const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const pageType = ref('add') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态
const userInfo = useUserStore()
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
const formInline: Ref<ISupplier> = ref({
  checkDate: null,
  checkName: '',
  checkNo: '',
  checkPerson: '',
  checkResult: '',
  checkResultName: '',
  createTime: null,
  createUser: userInfo.id,
  createUserName: userInfo.username,
  fileList: [
    {
      checkId: '',
      createTime: null,
      createUser: '',
      fileName: '',
      id: '',
      isDel: null,
      minioFileName: '',
      remark: '',
      updateTime: null,
    },
  ],
  id: '',
  isDel: null,
  managerPoinLocation: '',
  remark: '',
  updateTime: null,
})
const checkResultList = ref([
  { id: '1', name: '优', value: '1' },
  { id: '2', name: '良', value: '2' },
  { id: '3', name: '中', value: '3' },
  { id: '4', name: '差', value: '4' },
])
const companyAddress = ref<string[]>([]) // 公司地址
const invoiceAddress = ref<string[]>([]) // 开票地址
const ruleFormRef = ref<FormInstance>()
// 校验规则
const rules = ref({
  checkName: [{ required: true, message: '检查表名称', trigger: 'blur' }],
  checkPerson: [{ required: true, message: '检查人不能为空', trigger: 'blur' }],
  managerPoinLocation: [{ required: true, message: '管理点位置不能为空', trigger: 'blur' }],
  checkDate: [{ required: true, message: '检查日期不能为空', trigger: 'blur' }],
  createUser: [{ required: true, message: '管理点负责人不能为空', trigger: 'blur' }],
  checkResult: [{ required: true, message: '检查结果不能为空', trigger: 'blur' }],
  remark: [{ required: true, message: '内容描述不能为空', trigger: 'blur' }],
}) // 表单验证规则
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
const getInfo = () => {
  getselectCheckInfo({ id: infoId.value }).then((res) => {
    formInline.value = res.data
  })
}

// 打印表单
const printObj = ref({
  id: 'form', // 需要打印元素的id
  popTitle: '溯源供方详情', // 打印配置页上方的标题
  extraHead: '<div style="display: flex;flex-direction: column;text-align: center"><h3>溯源供方详情</h3></div>', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})

// 保存至草稿箱
function saveForm(formEl: FormInstance | undefined) {
  if (!formEl) { return }
  formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认提交吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (pageType.value === 'add') {
          getselectCheckInfo(formInline.value).then((res) => {
            if (res.code === '200') {
              close()
            }
          })
        }
        else if (pageType.value === 'edit') { // 编辑
          // getselectCheckInfo(formInline.value).then((res) => {
          //   if (res.code === '200') {
          //     close()
          //   }
          // })
        }
      })
    }
  })
}

// 提交表单
function submitForm() {
  if (formInline.value.id) {
    const params = {
      id: formInline.value.id,
      formId: SCHEDULE.SUPPLIER_APPROVAL, // 表单id
    }
    sourceSubmit(params).then((res) => {
      ElMessage.success('提交成功')
      close()
    })
  }
  else {
    ElMessage.info('请先保存再提交！')
  }
}
const isShow = ref(false)
const testForm = ref({
  fileList: [],
  fileContent: '',
})
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        formInline.value.fileList[0].minioFileName = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// 非添加页面获取详情
if (pageType.value !== 'add') {
  getInfo()
}
</script>

<template>
  <app-container>
    <detail-page :title="`设备管理点检查表-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType === 'detail'" v-print="printObj" type="primary">
          打印
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="saveForm(ruleFormRef)">
          提交
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <div id="form">
        <el-form
          ref="ruleFormRef"
          :model="formInline"
          :label-width="120"
          label-position="right"
          :rules="rules"
        >
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="检查表编号:" prop="checkNo">
                <el-input
                  v-model="formInline.checkNo"
                  :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检查表名称:" prop="checkName">
                <el-input
                  v-model="formInline.checkName"
                  :placeholder="pageType === 'detail' ? '' : '检查表名称'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检查人:" prop="checkPerson">
                <el-input
                  v-model="formInline.checkPerson"
                  :placeholder="pageType === 'detail' ? '' : '请输入检查人'"
                  :disabled="pageType === 'detail'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检查日期:" prop="checkDate">
                <el-date-picker
                  v-model="formInline.checkDate"
                  type="datetime"
                  placeholder="检查日期"
                  style="width: 100;"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY-MM-DD h:m:s"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="18">
              <el-form-item label="管理点位置:" prop="managerPoinLocation">
                <el-input
                  v-model="formInline.managerPoinLocation"
                  :placeholder="pageType === 'detail' ? '' : '请输入管理点位置'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="管理点负责人:" prop="createUser">
                <el-input
                  v-model="formInline.createUserName"
                  :placeholder="pageType === 'detail' ? '' : '请输入管理点负责人'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="检查结果:" prop="checkResult">
                <el-select
                  v-model.trim="formInline.checkResult"
                  clearable
                  placeholder="计量专业"
                  size="default"
                  :disabled="pageType === 'detail'"
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item in checkResultList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="12">
              <el-form-item label="内容描述:" prop="remark">
                <el-input
                  v-model="formInline.remark"
                  :placeholder="pageType === 'detail' ? '' : '请输入内容描述'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="14">
              <el-form-item label="附件:">
                <show-photo v-if="formInline.fileList[0].minioFileName" :minio-file-name="formInline.fileList[0].minioFileName" />
                <span v-else-if="pageType === 'detail'">无</span>
                <input v-show="pageType === ''" ref="fileRef" type="file" @change="onFileChange">
                <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': formInline.minioFileName === '' ? '0px' : '20px' }" @click="upload">
                  {{ formInline.fileList[0].minioFileName === '' ? '上传' : '更换附件' }}
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </detail-page>
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>
