<script lang="ts" setup name="ListSourceAdd">
import { reactive, ref } from 'vue'
import type { Ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import type { IOptions, IformInline } from './list_interface'
import { exportFile } from '@/utils/exportUtils'
import { UploadFile } from '@/api/measure/file'
import { getSoucreLisListExport, getSoucreLisUpdate, getSoucreListAdd, getSoucreListDetail, getSoucreListlevelType } from '@/api/system/source'
const props = defineProps({
  infoId: {
    type: String,
    default: '0',
  },
  buttonType: {
    type: String,
    default: '',
  },
})
const emit = defineEmits(['close'])
const formInline: Ref<IformInline> = ref({
  businessContent: null,
  supplierName: null,
  supplierNo: null,
  bankAccount: null,
  bankAccountNumber: null,
  bankName: null,
  briefName: null,
  businessScope: null,
  companyAddress: null,
  companyArea: null,
  companyCity: null,
  companyCountry: null,
  companyProvince: null,
  createTime: null,
  director: null,
  fax: null,
  invoiceAddress: null,
  invoiceArea: null,
  invoiceCity: null,
  invoiceCountry: null,
  invoiceProvince: null,
  mailbox: null,
  minioFileName: null,
  mobile: null,
  phone: null,
  postalCode: null,
  remark: null,
  taxNumber: null,
  website: null,
  traceSupplierPersonList: [],
})
const columns = [
  { text: '人员编号', value: 'personNo' },
  { text: '姓名', value: 'name' },
  { text: '工作部门', value: 'department' },
  { text: '职务', value: 'job' },
  { text: '联系方式', value: 'phone' },
]
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 addPersonList = ref({
  personNo: '',
  name: '',
  department: '',
  job: '',
  phone: '',
})
const SelectionList = ref([])
const upload = ref<UploadInstance>()
const close = () => {
  emit('close')
}
const getInfo = () => {
  getSoucreListDetail({ id: props.infoId }).then((res) => {
    formInline.value = res.data
  })
}
// 表格选中
const handleSelectionChange = (e: any) => {
  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 addRoow = () => {
  Object.keys(addPersonList.value).forEach(key => (addPersonList.value[key] = ''))
  dialogVisible.value = true
}
// 点击关闭
const handleClose = () => {
  dialogVisible.value = false
}
// 点击弹窗的完成追加到表格数组中
const addPushList = () => {
  formInline.value.traceSupplierPersonList.push(JSON.parse(JSON.stringify(addPersonList.value)))
  handleClose()
}
// 删除行
const deleteList = () => {
  formInline.value.traceSupplierPersonList = formInline.value.traceSupplierPersonList.filter((item) => {
    return !SelectionList.value.includes(item)
  })
}
// 点击提交/导出按钮
const getAddList = (type: string) => {
  if (formInline.value.supplierNo === null) {
    return ElMessage.error('请填写溯源供方编号')
  }
  else if (formInline.value.supplierName === null) {
    return ElMessage.error('请填写公司名称')
  }
  else if (formInline.value.businessContent === null) {
    return ElMessage.error('请填写业务内容')
  }
  else if (formInline.value.taxNumber === null) {
    return ElMessage.error('请填写税号')
  }
  if (type === '提交' && props.buttonType !== '编辑') {
    getSoucreListAdd(formInline.value).then((res) => {
      if (res.code === 200) {
        close()
      }
    })
  }
  else if (type === '提交' && props.buttonType === '编辑') {
    formInline.value.id = props.infoId
    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 handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning('只能上传一个文件')
}
// 移除时触发
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `确认移除${uploadFile.name}文件吗 ?`,
  ).then(
    () => true,
    () => false,

  )
}
const isShow = ref(false)
const testForm = ref({
  fileList: [],
  fileContent: '',
})
const handleFileChange = (files: any, fileList: any) => {
  testForm.value.fileList = fileList
  const reader = new FileReader()
  reader.readAsText(files.raw)
  reader.onload = (e) => {
    testForm.value.fileContent = e.target!.result?.replace(
      /\n|\r\n/g,
      '<br/>',
    )
  }
}
// 点击文件预览
const uploadShow = (e: any) => {
  const URL = window.URL || window.webkitURL
  window.open(URL.createObjectURL(e.raw))
}
// 上传请求
const uploadQuarterlyEvaluateFile = (file: File) => {
  const fd = new FormData()
  fd.append('multipartFile', file.file)
  UploadFile(fd).then((res) => {
    if (res.code === 200) {
      formInline.value.minioFileName = res.data.fileName
      // fileList.value.push({
      //   name: res.data.fileName,
      //   url: res.data.fileId,
      //   // type: file.file.type,
      // })
      // 重置当前验证
      ElMessage.success('文件上传成功')
    }
  })
}
if (props.buttonType !== '') {
  getInfo()
}
</script>

<template>
  <app-container>
    <div class="top-info">
      <h4 class="title">
        基本信息
      </h4>
      <div>
        <el-button type="primary" @click="getAddList(buttonType === '详情' ? '导出' : '提交')">
          {{ buttonType === '详情' ? '导出' : '提交' }}
        </el-button>
        <el-button type="warning" @click="close">
          关闭
        </el-button>
      </div>
    </div>
    <div class="info-content">
      <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
        label-width="100"
        label-position="left"
      >
        <div class="content-top">
          <span>
            <el-form-item label="溯源供方编号:">
              <el-input
                v-model="formInline.supplierNo"
                :placeholder="buttonType === '详情' ? '无' : '请输入溯源供方编号'"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
            <el-form-item label="税号:">
              <el-input v-model="formInline.taxNumber" :placeholder="buttonType === '详情' ? '无' : '请输入税号'" :disabled="buttonType === '详情'" />
            </el-form-item>
            <el-form-item label="邮编:">
              <el-input v-model="formInline.postalCode" :placeholder="buttonType === '详情' ? '无' : '请输入邮编'" :disabled="buttonType === '详情'" />
            </el-form-item>
            <el-form-item label="手机:">
              <el-input v-model="formInline.mobile" :placeholder="buttonType === '详情' ? '无' : '请输入手机'" :disabled="buttonType === '详情'" />
            </el-form-item>
          </span>
          <span>
            <el-form-item label="公司名称:">
              <el-input
                v-model="formInline.supplierName"
                :placeholder="buttonType === '详情' ? '无' : '请输入公司名称'"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
            <el-form-item label="银行账户名:">
              <el-input
                v-model="formInline.bankAccount"
                :placeholder="buttonType === '详情' ? '无' : '请输入银行账户名'"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
            <el-form-item label="负责人:">
              <el-input v-model="formInline.director" :placeholder="buttonType === '详情' ? '无' : '请输入负责人'" :disabled="buttonType === '详情'" />
            </el-form-item>
            <el-form-item label="邮箱:">
              <el-input v-model="formInline.mailbox" :placeholder="buttonType === '详情' ? '无' : '请输入邮箱'" :disabled="buttonType === '详情'" />
            </el-form-item>
          </span>
          <span>
            <el-form-item label="公司简称:">
              <el-input v-model="formInline.briefName" :placeholder="buttonType === '详情' ? '无' : '请输入公司简称'" :disabled="buttonType === '详情'" />
            </el-form-item>
            <el-form-item label="银行名称:">
              <el-input v-model="formInline.bankName" :placeholder="buttonType === '详情' ? '无' : '请输入银行名称'" :disabled="buttonType === '详情'" />
            </el-form-item>
            <el-form-item label="电话:">
              <el-input v-model="formInline.phone" :placeholder="buttonType === '详情' ? '无' : '请输入电话'" :disabled="buttonType === '详情'" />
            </el-form-item>
            <el-form-item label="网址:">
              <el-input v-model="formInline.website" :placeholder="buttonType === '详情' ? '无' : '请输入网址'" :disabled="buttonType === '详情'" />
            </el-form-item>
          </span>
          <span>
            <el-form-item label="业务内容:">
              <el-input
                v-model="formInline.businessContent"
                :placeholder="buttonType === '详情' ? '无' : '请输入业务内容'"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
            <el-form-item label="银行账号:">
              <el-input
                v-model="formInline.bankAccountNumber"
                :placeholder="buttonType === '详情' ? '无' : '请输入银行账号'"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
            <el-form-item label="传真:">
              <el-input v-model="formInline.fax" :placeholder="buttonType === '详情' ? '无' : '请输入传真'" :disabled="buttonType === '详情'" />
            </el-form-item>
          </span>
        </div>
        <div class="info-dizhi">
          <el-form-item label="公司地址:">
            <el-select v-model="formInline.companyCountry" placeholder="国别" :disabled="buttonType === '详情'">
              <el-option label="中国" value="中国" />
            </el-select>
            <el-select v-model="formInline.companyProvince" placeholder="省" :disabled="buttonType === '详情'" @click="getCompanyAddress('0')" @change="changeProvince">
              <el-option v-for="province in provinceList" :key="province.id" :label="province.areaName" :value="province.id" />
            </el-select>
            <el-select v-model="formInline.companyCity" placeholder="市" :disabled="buttonType === '详情'" @change="cityChange">
              <el-option v-for="city in cityList" :key="city.id" :label="city.areaName" :value="city.id" />
            </el-select>
            <el-select v-model="formInline.companyArea" placeholder="区/县" :disabled="buttonType === '详情'">
              <el-option v-for="area in areaList" :key="area.id" :label="area.areaName" :value="area.id" />
            </el-select>
            <el-input
              v-model="formInline.companyAddress"
              placeholder="公司详细地址"
              :disabled="buttonType === '详情'"
            />
          </el-form-item>
        </div>
        <div class="info-dizhi">
          <el-form-item label="开票地址:">
            <el-select v-model="formInline.invoiceCountry" placeholder="国别" :disabled="buttonType === '详情'">
              <el-option label="中国" value="中国" />
            </el-select>
            <el-select v-model="formInline.invoiceProvince" placeholder="省" :disabled="buttonType === '详情'" @click="getinvoiceProvinceList('0')" @change="changeInvoice">
              <el-option v-for="province in invoiceProvince" :key="province.id" :label="province.areaName" :value="province.id" />
            </el-select>
            <el-select v-model="formInline.invoiceCity" placeholder="市" :disabled="buttonType === '详情'" @change="invoiceCityChange">
              <el-option v-for="city in invoiceCityList" :key="city.id" :label="city.areaName" :value="city.id" />
            </el-select>
            <el-select v-model="formInline.invoiceArea" placeholder="区/县" :disabled="buttonType === '详情'">
              <el-option v-for="area in areaInvoiceList" :key="area.id" :label="area.areaName" :value="area.id" />
            </el-select>
            <el-input
              v-model="formInline.invoiceAddress"
              placeholder="开票详细地址"
              :disabled="buttonType === '详情'"
            />
          </el-form-item>
        </div>
        <span class="input-width">
          <el-form-item label="公司业务范围:">
            <el-input
              v-model="formInline.businessScope"
              :placeholder="buttonType === '详情' ? '无' : '请输入公司业务范围'"
              :disabled="buttonType === '详情'"
            />
          </el-form-item>
        </span>
        <span class="input-width">
          <el-form-item label="备注:">
            <el-input v-model="formInline.remark" :placeholder="buttonType === '详情' ? '无' : '请输入备注'" :disabled="buttonType === '详情'" />
          </el-form-item>
        </span>
        <div class="info-appendix">
          <el-form-item label="附件:">
            <el-upload
              v-model:file-list="fileList"
              enctype="multipart/form-data"
              :http-request="uploadQuarterlyEvaluateFile"
              :before-remove="beforeRemove"
              :on-exceed="handleExceed"
              :on-preview="uploadShow"
              :on-change="handleFileChange"
              :limit="1"
            >
              <el-button :disabled="buttonType === '详情'">
                上传
              </el-button>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="table-top">
      <div class="table-top-title">
        人员信息
      </div>
      <div class="table-top-button">
        <el-button :disabled="buttonType === '详情'" @click="deleteList">
          删除行
        </el-button>
        <el-button :disabled="buttonType === '详情'" @click="addRoow">
          增加行
        </el-button>
      </div>
    </div>
    <el-table :data="formInline.traceSupplierPersonList" border style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <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" />
    </el-table>
  </app-container>
  <el-dialog
    v-model="dialogVisible"
    title="添加人员信息"
    width="30%"
    :before-close="handleClose"
    center
  >
    <el-form
      ref="addPersonListForm"
      label-position="left"
      label-width="100px"
      :model="addPersonList"
      style="max-width: 460px;"
    >
      <el-form-item v-for="column in columns" :key="column.value" :label="column.text" :prop="addPersonList[column.value]">
        <el-input v-model="addPersonList[column.value]" />
      </el-form-item>
    </el-form>
    <el-button type="primary" class="dialog-button" @click="addPushList">
      完成
    </el-button>
  </el-dialog>
  <!-- <el-dialog
        title="文件预览"
        :visible="isShow"
        @close="isShow = false"
        width="40%"
        append-to-body
      >
        <div v-html="testForm.fileContent"></div>
      </el-dialog> -->
</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>
