<!-- 添加/编辑 -->
<template>
  <el-dialog :title="title" :visible.sync="isShow" :close-on-click-modal="false" class="drawer-box" width="1000px" @close="handleCancel" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="top">
      <el-row>
        <el-col :span="7">
          <el-form-item label="营业执照:" required>
            <div class="upload-box">
              <div style="margin-right: 16px;text-align: center;">
                <imageUpload :fileSize="2" isBorder v-model="form.logo" :value="form.logo" :limit="1" @change="handleFileList" />
                <el-button type="primary" style="margin-top:15px;" :loading="scanLoading" @click="handleBeginScan" :disabled="disabled" size="small">营业执照识别</el-button>
              </div>
              <!-- <div class="upload-lf">
              </div> -->
              <!-- <div class="upload-rt">
              </div> -->
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="16" class="bl-soild">
          <el-row>
            <el-col :span="12">
              <el-form-item label="企业名称" prop="companyAme">
                <el-input v-model="form.companyAme" placeholder="请输入" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业性质" prop="companyType">
                <el-select v-model="form.companyType" clearable class="wd100" size="small">
                  <el-option v-for="item in enterpriseList" :key="item.id" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="法人代表" prop="legalPerson">
                <el-input v-model="form.legalPerson" placeholder="请输入" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入" size="small"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="统一社会信用代码" prop="creditCode">
                <el-input v-model="form.creditCode" placeholder="请输入" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业住所" prop="address">
                <el-input v-model="form.address" placeholder="请输入" size="small"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="营业期限" prop="date">
                <el-date-picker v-model="form.date" @change="handleDateChange" size="small" class="wd100" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册资本" prop="capital">
                <el-input v-model="form.capital" placeholder="请输入" size="small">
                  <template slot="append">万元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="银行户名" prop="bankName">
                <el-input v-model="form.bankName" placeholder="请输入" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行账号" prop="bankNumber">
                <el-input v-model="formattedBankNumber" placeholder="请输入" size="small"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开户行名称" prop="bankOfDeposit">
                <el-input v-model="form.bankOfDeposit" placeholder="请输入" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否注册" prop="isRegister">
                <el-radio-group v-model="form.isRegister">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" size="small" @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="btnLoading" :disabled="disabled" size="small" @click="handleSave">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { baiduScanApi, createSupplierCompany, updateSupplierCompany, getSupplierCompany } from '@/api/procurement/supplierMsg'
import VerifyFunc from '@/utils/verity'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);
export default {
  name: '',
  props: {
    id: [String, Number],
    isOpen: Boolean,
    disabled: Boolean,
    enterpriseList: Array,
  },
  computed: {
    formattedBankNumber: {
      get() {
        return this.form.bankNumber.replace(/\s/g, '').replace(/(.{4})/g, '$1 ');
      },
      set(value) {
        this.form.bankNumber = value.replace(/\s/g, '');
      }
    }
  },
  components: {
    ImageUpload: () => import('@/components/ImageUpload'),
  },
  created() {
  },
  watch: {
    fileList: {
      handler(list) {
        if (list && list.length) {
          this.$nextTick(() => {
            // this.$set(this.form, 'logo', list)
            this.$refs.form.clearValidate(['logo'])
          })
        } else {
          this.$set(this.form, 'logo', null)
        }
      },
      deep: true
    },
    isOpen: {
      handler(val) {
        this.isShow = val
        this.title = this.disabled ? '供应商信息' : this.id ? '编辑供应商信息' : '新增供应商信息'
        if (val) {
          this.handleInitForm()
          // this.handleInitList(this.id)
        }
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      scanLoading: false,
      btnLoading: false,
      dialogVisible: false,
      dialogImageUrl: null,
      provinceList: [],
      isShow: false,
      title: '',
      rules: {
        companyAme: [{ required: true, message: '请输入', trigger: 'blur' }],
        companyType: [{ required: true, message: '请选择', trigger: 'change' }],
        legalPerson: [{ required: true, message: '请输入', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: VerifyFunc.rePhone, trigger: 'blur' }
        ],
        creditCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        address: [{ required: true, message: '请输入', trigger: 'blur' }],
        date: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        capital: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: VerifyFunc.newNumber, trigger: 'blur' }
        ],
        bankName: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        bankNumber: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: VerifyFunc.validateBank, trigger: 'blur' }
        ],
        bankOfDeposit: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        isRegister: [
          { required: true, message: '请选择', trigger: 'change' },
        ]
      },
      form: {
        logo: null,
        companyAme: null,
        companyType: '',
        legalPerson: null,
        phone: '',
        creditCode: '',
        address: '',
        date: null,
        capital: null,
        bankName: '',
        bankNumber: '',
        bankOfDeposit: null,
        isRegister: 1,
        businessStratDate: null,
        businessEndDate: null,
      },
      nameArr: [],
      fileList: [],
      isDisabled: true,
    }
  },

  methods: {
    handleDateChange(list) {
      this.$set(this.form, 'businessStratDate', list.length ? dayjs(list[0]).valueOf() : null)
      this.$set(this.form, 'businessEndDate', list.length ? dayjs(list[1]).valueOf() : null)
      console.log('list...', this.form);
    },
    handleFileList(fileList) {
      this.fileList = fileList
      // this.$set(this.form, 'logo', fileList)
    },
    handleBeginScan() {
      if (!(this.fileList && this.fileList.length)) {
        return this.$fm('请上传营业执照！')
      }
      const { url } = this.fileList[0]
      let formData = new FormData()
      formData.append('url', url)
      this.scanLoading = true
      baiduScanApi(formData).then((res) => {
        // this.form = 
        const { unitName, legalPerson, code, registeredCapital, address, companyCreateDate, validity } = res.data
        let startTime = companyCreateDate && dayjs(companyCreateDate, 'YYYY年MM月DD日').format('YYYY-MM-DD') ? dayjs(companyCreateDate, 'YYYY年MM月DD日').format('YYYY-MM-DD') : null
        let endTime = validity && dayjs(validity, 'YYYY年MM月DD日').format('YYYY-MM-DD') ? dayjs(validity, 'YYYY年MM月DD日').format('YYYY-MM-DD') : null
        this.form = {
          ...this.form,
          companyAme: unitName,
          legalPerson,
          creditCode: code,
          address,
          capital: registeredCapital && registeredCapital.indexOf('万元') > -1 ? registeredCapital.split('万元')[0] : registeredCapital,
          isRegister: 1,
          date: [startTime ? new Date(startTime) : null, endTime ? new Date(endTime) : null],
          businessStratDate: dayjs(startTime).valueOf(),
          businessEndDate: dayjs(endTime).valueOf(),
          status: 1,
        }
        console.log('this.form..', this.form);
        this.scanLoading = false
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.clearValidate()
        })
      }).catch(() => {
        this.scanLoading = false
      })
    },
    handleDel() {
      delSchoolListApi(this.id).then(() => {
        this.$sm('删除成功!')
        this.$emit('onConfirm')
      })
    },
    // id 不存在 新增 否则编辑
    handleInitForm(id = this.id) {
      // 初始化参数
      if (!id) {
        this.form = {
          logo: null,
          companyAme: null,
          companyType: '',
          legalPerson: null,
          phone: '',
          creditCode: '',
          address: '',
          date: null,
          capital: null,
          bankName: '',
          bankNumber: '',
          bankOfDeposit: null,
          isRegister: 1,
          businessStratDate: null,
          businessEndDate: null,

        }
        this.fileList = []
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.resetFields()
          this.$refs.form && this.$refs.form.clearValidate()
        })
      } else {
        getSupplierCompany(id).then(res => {
          this.form = {
            ...(res.data || {}),
            logo: res.data.files,
            date: [res.data.businessStratDate ? new Date(res.data.businessStratDate) : null, res.data.businessEndDate ? new Date(res.data.businessEndDate) : null]
          }
          this.fileList = this.form.files
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate()
          })
        })
      }
    },
    // 0 新增 1 编辑
    handleInitList(id) {
      queryEnrollAppListApi().then(res => {
        this.nameArr = res.data || []
        if (this.nameArr.length == 1) {
          if (!id) {
            this.isDisabled = true
            this.form.appletId = this.nameArr[0].id
          } else {
            this.isDisabled = false
          }
        } else {
          this.isDisabled = false
        }
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleClose() {
      this.$emit('onClose')
    },

    handleSave() {
      this.$nextTick(() => {
        this.$refs.form.validate((bool) => {
          if (bool) {
            if (!this.fileList.length) {
              this.$fm('请上传营业执照!')
              return
            }
            let form = {
              ...this.form,
              files: this.fileList
            }
            // 编辑
            this.$modal.loading("提交中，请稍候...");
            if (this.id) {
              updateSupplierCompany(form).then(() => {
                this.$modal.msgSuccess("修改成功！");
                this.$modal.closeLoading()
                this.$emit('onConfirm')
              }).catch(() => {
                this.$modal.closeLoading()
              })
            } else {
              // 新增
              createSupplierCompany(form).then(() => {
                this.$modal.msgSuccess("新增成功！");
                this.$modal.closeLoading()
                this.$emit('onConfirm')
              }).catch(() => {
                this.$modal.closeLoading()
              })
            }
          }
        })
      })
    },
    handleCancel() {
      this.$emit('onClose')
    },
    handleRemove(file, files) {
      this.fileList = []
      this.form.logoUrl = null
    },
    onUploadChange(file, files) {
      if (['image/png', 'image/jpeg'].includes(file.raw.type)) {
        if (file.size / 1024 > 5000) {
          setTimeout(() => {
            this.$fm('文件超过5Mb，请压缩后上传!')
          }, 10)
          files.splice(files.length - 1, 1)
          return
        }
        this.fileList = []
        this.fileList.push(file)
      } else {
        this.$fm('不支持此文件类型，请重试！')
      }
    },
  }
}

</script>
<style lang='scss' scoped>
@import '@/assets/styles/edit/index.scss';
.bl-soild {
  border-left: 1px solid #cccccc;
  box-sizing: border-box;
  padding-left: 50px;
}
</style>