<script lang="ts" setup name="ListSourceAdd">
/**
 * 添加/编辑/详情溯源供方
 */
import type { Ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadInstance, UploadProps, UploadUserFile } from 'element-plus'
import type { IOptions, IformInline, traceSupplierPerson } from './list_interface'
import { exportFile } from '@/utils/exportUtils'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { UploadFile } from '@/api/measure/file'
import { getSoucreLisListExport, getSoucreLisUpdate, getSoucreListAdd, getSoucreListDetail, getSoucreListlevelType } from '@/api/system/source'
import { validatePhone } from '@/utils/validate'
const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const pageType = ref('add') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态
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<IformInline> = ref({
  id: '',
  businessContent: '',
  supplierName: '',
  supplierNo: '',
  bankAccount: '',
  bankAccountNumber: '',
  bankName: '',
  briefName: '',
  businessScope: '',
  companyAddress: '',
  companyArea: '',
  companyCity: '',
  companyCountry: '',
  companyProvince: '',
  createTime: '',
  director: '',
  fax: '',
  invoiceAddress: '',
  invoiceArea: '',
  invoiceCity: '',
  invoiceCountry: '',
  invoiceProvince: '',
  mailbox: '',
  minioFileName: '',
  mobile: '',
  phone: '',
  postalCode: '',
  remark: '',
  taxNumber: '',
  website: '',
  traceSupplierPersonList: [],
})
const traceSupplierPersonList: Ref<traceSupplierPerson[]> = ref([])
const columns = ref([
  { text: '人员编号', value: 'personNo', required: false },
  { text: '姓名', value: 'name', required: true },
  { text: '工作部门', value: 'department', required: false },
  { text: '职务', value: 'job', required: false },
  { text: '联系方式', value: 'phone', required: true, reg: validatePhone },
])
const ruleFormRef = ref<FormInstance>()
const provinceList = ref<IOptions[]>([])
const fileList = ref<UploadUserFile[]>([])
const cityList = ref<IOptions[]>([])
const areaList = ref<IOptions[]>([])
const invoiceProvince = ref<IOptions[]>([])
const invoiceCityList = ref<IOptions[]>([])
const areaInvoiceList = ref<IOptions[]>([])
const dialogVisible = ref(false)
// 人员对象
const addPersonObj: traceSupplierPerson = {
  id: '',
  personNo: '',
  name: '',
  department: '',
  job: '',
  phone: '',
  editable: true,
}
const SelectionList: Ref<traceSupplierPerson[]> = ref([])
// 校验规则
const rules = ref({
  supplierNo: [{ required: true, message: '溯源供方编号不能为空', trigger: 'blur' }],
  supplierName: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
  businessContent: [{ required: true, message: '业务内容不能为空', trigger: 'blur' }],
  taxNumber: [{ required: true, message: '税号不能为空', trigger: 'blur' }],
}) // 表单验证规则
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
const getInfo = () => {
  getSoucreListDetail({ id: infoId.value }).then((res) => {
    formInline.value = res.data
  })
}
// 表格选中
const handleSelectionChange = (e: traceSupplierPerson[]) => {
  SelectionList.value = e
}
// 获取公司地址省级
const getCompanyAddress = (type: string) => {
  getSoucreListlevelType(type).then((res) => {
    provinceList.value = res.data
  })
}

// 公司地址省级的值发生改变
const changeProvince = (e: any) => {
  cityList.value = []
  areaList.value = []
  formInline.value.companyCity = ''
  formInline.value.companyArea = ''

  getSoucreListlevelType(e).then((res) => {
    cityList.value = res.data
  })
}
// 公司地址市级发生改变
const cityChange = (e: any) => {
  areaList.value = []
  formInline.value.companyArea = ''
  getSoucreListlevelType(e).then((res) => {
    areaList.value = res.data
  })
}
// 获取到开票地址省级
const getinvoiceProvinceList = (type: string) => {
  getSoucreListlevelType(type).then((res) => {
    invoiceProvince.value = res.data
  })
}
// 开票地址省级发生改变
const changeInvoice = (e: any) => {
  formInline.value.invoiceCity = ''
  formInline.value.invoiceArea = ''
  getSoucreListlevelType(e).then((res) => {
    invoiceCityList.value = res.data
  })
}
// 开票地址市级发生改变
const invoiceCityChange = (e: string) => {
  formInline.value.invoiceArea = ''
  getSoucreListlevelType(e).then((res) => {
    areaInvoiceList.value = res.data
  })
}
// 点击增加行
const addRow = () => {
  // 检查上一行必填项
  if (checkPersonList()) {
    setAllRowReadable()
    traceSupplierPersonList.value.push({ ...addPersonObj })
  }
}
// 检查人员列表
function checkPersonList() {
  for (let index = 0; index < traceSupplierPersonList.value.length; index++) {
    const item = traceSupplierPersonList.value[index]
    for (const prop of columns.value) {
      // 检查必填
      if (prop.required && !item[prop.value]) {
        ElMessage.warning(`请先完善第${index + 1}行中${prop.text}`)
        return false
      }
      // 验证正则
      if (prop.reg && typeof prop.reg === 'function') {
        if (!prop.reg(item[prop.value])) {
          ElMessage.warning(`第${index + 1}行中${prop.text}输入不合法`)
          return false
        }
      }
    }
  }
  return true
}
// 点击关闭
const handleClose = () => {
  dialogVisible.value = false
}
// 点击弹窗的完成追加到表格数组中
const addPushList = () => {
  formInline.value.traceSupplierPersonList.push(JSON.parse(JSON.stringify(addPersonObj.value)))
  handleClose()
}
// 删除行
const deleteList = () => {
  traceSupplierPersonList.value = traceSupplierPersonList.value.filter((item: traceSupplierPerson) => {
    return !SelectionList.value.includes(item)
  })
}
// 点击提交/导出按钮
const getAddList = async (formEl: FormInstance | undefined, type: string) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
    `确认${type}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
      ).then(() => {
        if (type === '提交' && pageType.value !== 'edit') {
          getSoucreListAdd(formInline.value).then((res) => {
            if (res.code === 200) {
              close()
            }
          })
        }
        else if (type === '提交' && pageType.value === 'edit') {
          formInline.value.id = infoId.value
          getSoucreLisUpdate(formInline.value).then((res) => {
            if (res.code === 200) {
              close()
            }
          })
        }
        else {
          const params = {
            businessContent: formInline.value.businessContent,
            supplierName: formInline.value.supplierName,
            supplierNo: formInline.value.supplierNo,
          }
          getSoucreLisListExport(params).then((res) => {
            exportFile(res.data, '溯源供方详情')
          })
        }
      })
    }
  })
}
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.minioFileName = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// 双击行显示输入框
const dblclickRow = (row: traceSupplierPerson) => {
  setAllRowReadable()
  row.editable = true
}
// 将所有人员信息列表置为不可编辑状态
function setAllRowReadable() {
  for (const item of traceSupplierPersonList.value) {
    item.editable = false
  }
}
if (pageType.value !== 'add') {
  getInfo()
}
</script>

<template>
  <app-container>
    <detail-page :title="`溯源供方-${textMap[pageType]}`">
      <template #btns>
        <el-button
          type="primary"
          @click="
            getAddList(ruleFormRef, pageType === 'detail' ? '导出' : '提交')
          "
        >
          {{ pageType === 'detail' ? '导出' : '提交' }}
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="formInline"
        class="demo-form-inline"
        label-width="auto"
        label-position="right"
        :rules="rules"
      >
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="溯源供方编号:" prop="supplierNo">
              <el-input
                v-model="formInline.supplierNo"
                :placeholder="
                  pageType === 'detail' ? '无' : '请输入溯源供方编号'
                "
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="税号:" prop="taxNumber">
              <el-input
                v-model="formInline.taxNumber"
                :placeholder="pageType === 'detail' ? '无' : '请输入税号'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="邮编:">
              <el-input
                v-model="formInline.postalCode"
                :placeholder="pageType === 'detail' ? '无' : '请输入邮编'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机:">
              <el-input
                v-model="formInline.mobile"
                :placeholder="pageType === 'detail' ? '无' : '请输入手机'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="公司名称:" prop="supplierName">
              <el-input
                v-model="formInline.supplierName"
                :placeholder="pageType === 'detail' ? '无' : '请输入公司名称'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="银行账户名:">
              <el-input
                v-model="formInline.bankAccount"
                :placeholder="pageType === 'detail' ? '无' : '请输入银行账户名'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="负责人:">
              <el-input
                v-model="formInline.director"
                :placeholder="pageType === 'detail' ? '无' : '请输入负责人'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="邮箱:">
              <el-input
                v-model="formInline.mailbox"
                :placeholder="pageType === 'detail' ? '无' : '请输入邮箱'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="公司简称:">
              <el-input
                v-model="formInline.briefName"
                :placeholder="pageType === 'detail' ? '无' : '请输入公司简称'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="银行名称:">
              <el-input
                v-model="formInline.bankName"
                :placeholder="pageType === 'detail' ? '无' : '请输入银行名称'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电话:">
              <el-input
                v-model="formInline.phone"
                :placeholder="pageType === 'detail' ? '无' : '请输入电话'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="网址:">
              <el-input
                v-model="formInline.website"
                :placeholder="pageType === 'detail' ? '无' : '请输入网址'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="业务内容:" prop="businessContent">
              <el-input
                v-model="formInline.businessContent"
                :placeholder="pageType === 'detail' ? '无' : '请输入业务内容'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="银行账号:">
              <el-input
                v-model="formInline.bankAccountNumber"
                :placeholder="pageType === 'detail' ? '无' : '请输入银行账号'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="传真:">
              <el-input
                v-model="formInline.fax"
                :placeholder="pageType === 'detail' ? '无' : '请输入传真'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-form-item label="公司地址:">
            <el-col :span="4">
              <el-select
                v-model="formInline.companyCountry"
                placeholder="国别"
                :disabled="pageType === 'detail'"
              >
                <el-option label="中国" value="中国" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select
                v-model="formInline.companyProvince"
                placeholder="省"
                :disabled="pageType === 'detail'"
                @click="getCompanyAddress('0')"
                @change="changeProvince"
              >
                <el-option
                  v-for="province in provinceList"
                  :key="province.id"
                  :label="province.areaName"
                  :value="province.id"
                />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select
                v-model="formInline.companyCity"
                placeholder="市"
                :disabled="pageType === 'detail'"
                @change="cityChange"
              >
                <el-option
                  v-for="city in cityList"
                  :key="city.id"
                  :label="city.areaName"
                  :value="city.id"
                />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select
                v-model="formInline.companyArea"
                placeholder="区/县"
                :disabled="pageType === 'detail'"
              >
                <el-option
                  v-for="area in areaList"
                  :key="area.id"
                  :label="area.areaName"
                  :value="area.id"
                />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-input
                v-model="formInline.companyAddress"
                placeholder="公司详细地址"
                :disabled="pageType === 'detail'"
              />
            </el-col>
          </el-form-item>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-form-item label="开票地址:">
            <el-col :span="4">
              <el-select
                v-model="formInline.invoiceCountry"
                placeholder="国别"
                :disabled="pageType === 'detail'"
              >
                <el-option label="中国" value="中国" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select
                v-model="formInline.invoiceProvince"
                placeholder="省"
                :disabled="pageType === 'detail'"
                @click="getinvoiceProvinceList('0')"
                @change="changeInvoice"
              >
                <el-option
                  v-for="province in invoiceProvince"
                  :key="province.id"
                  :label="province.areaName"
                  :value="province.id"
                />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select
                v-model="formInline.invoiceCity"
                placeholder="市"
                :disabled="pageType === 'detail'"
                @change="invoiceCityChange"
              >
                <el-option
                  v-for="city in invoiceCityList"
                  :key="city.id"
                  :label="city.areaName"
                  :value="city.id"
                />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select
                v-model="formInline.invoiceArea"
                placeholder="区/县"
                :disabled="pageType === 'detail'"
              >
                <el-option
                  v-for="area in areaInvoiceList"
                  :key="area.id"
                  :label="area.areaName"
                  :value="area.id"
                />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-input
                v-model="formInline.invoiceAddress"
                placeholder="开票详细地址"
                :disabled="pageType === 'detail'"
              />
            </el-col>
          </el-form-item>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="14">
            <el-form-item label="公司业务范围:">
              <el-input
                v-model="formInline.businessScope"
                :placeholder="
                  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="备注:">
              <el-input
                v-model="formInline.remark"
                :placeholder="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 :minio-file-name="formInline.minioFileName" />
              <input v-show="pageType === ''" ref="fileRef" type="file" @change="onFileChange">
              <el-button type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': formInline.minioFileName === '' ? '0px' : '20px' }" @click="upload">
                {{ formInline.minioFileName === '' ? '上传' : '更换附件' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="人员信息">
      <template v-if="pageType !== 'detail'" #btns>
        <el-button type="info" @click="deleteList">
          删除行
        </el-button>
        <el-button type="primary" @click="addRow">
          增加行
        </el-button>
      </template>
      <el-table
        :data="traceSupplierPersonList"
        border
        style="width: 100%;"
        @selection-change="handleSelectionChange"
        @row-dblclick="dblclickRow"
      >
        <el-table-column type="selection" width="38" />
        <el-table-column align="center" label="序号" width="80" type="index" />
        <el-table-column
          v-for="item in columns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
          align="center"
        >
          <template #header>
            <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
          </template>
          <template #default="scope">
            <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>
            <el-input v-else v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="input" />
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
  </app-container>
</template>

<style lang="scss" scoped>
.top-info {
  width: 100%;
  height: 50px;
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 10px;
  background-color: #fff;

  .title {
    width: 75%;
    text-align: center;
  }
}

.info-content {
  margin-top: 10px;
  padding: 30px;
  border-radius: 10px;
  background-color: #fff;

  .content-top {
    display: flex;
    justify-content: space-around;
  }

  .info-dizhi {
    margin-right: 155px;
  }
}

.el-select {
  width: 9vw;
  margin-right: 15px;
}

.info-dizhi .el-input {
  width: 20vw;
}

.input-width .el-input {
  width: 30vw;
}

.info-appendix span {
  margin-right: 25px;
}

.table-top {
  margin-top: 10px;
  padding: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 10px;
  background-color: #fff;

  .table-top-title {
    width: 60vw;
    text-align: center;
  }
}

.dialog-button {
  margin-left: 50%;
  transform: translateX(-50%);
}
</style>
