<template>
  <!-- 表单渲染 -->
  <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelView" :visible="visible" :title="title" width="860px">
    <el-form ref="formViewRef" :model="formData" :rules="rules" :status-icon="true" label-width="240px">
      <el-form-item label="标识设置：" class="form-cell" prop="supplierLevel">
        <div class="cell-box">
          <el-radio-group v-model="formData.supplierLevel" size="mini">
            <el-radio v-for="item in dict.supplier_rank" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
      <el-form-item label="企业名称：" class="form-cell" prop="enterpriseName">
        <div class="cell-box">
          <el-input v-model="formData.enterpriseName" placeholder="请输入企业名称" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="企业联系人：" class="form-cell" prop="enterpriseContactPerson">
        <div class="cell-box">
          <el-input v-model="formData.enterpriseContactPerson" placeholder="请输入联系人" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="企业联系人手机号：" class="form-cell" prop="enterpriseContactPersonPhone">
        <div class="cell-box">
          <el-input v-model="formData.enterpriseContactPersonPhone" placeholder="请输入手机号" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="企业地址：" class="form-cell" prop="enterpriseAddress">
        <div class="cell-box">
          <el-input v-model="formData.enterpriseAddress" placeholder="请输入地址" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="企业邮箱：" class="form-cell" prop="enterpriseEmail">
        <div class="cell-box">
          <el-input v-model="formData.enterpriseEmail" placeholder="请输入邮箱" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="营业执照：" class="form-cell" prop="businessLicense">
        <div class="cell-box">
          <ul class="el-upload-list el-upload-list--picture-card" style="float: left">
            <li v-for="(item, index) in imgList" :key="index" tabindex="0" class="el-upload-list__item is-success">
              <img :src="imgSrcStart+'/businessLicense/'+item" class="el-upload-list__item-thumbnail">
              <label class="el-upload-list__item-status-label"><i class="el-icon-upload-success el-icon-check" /></label>
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="dialogImgUrl=item;dialogImgVisible=true"><i class="el-icon-zoom-in" /></span>
                <span class="el-upload-list__item-delete" @click="handleRemoveImg(item)"><i class="el-icon-delete" /></span>
              </span>
            </li>
          </ul>
          <el-dialog append-to-body :visible.sync="dialogImgVisible">
            <img width="100%" :src="imgSrcStart+'/businessLicense/'+dialogImgUrl">
          </el-dialog>
          <el-upload
            ref="uploadCom"
            action="/api/bsw/users/uploadBusinessLicense"
            name="businessLicense"
            list-type="picture-card"
            :headers="uploadHeaders"
            :limit="2"
            :before-upload="handleProgress"
            :on-exceed="handleExceed"
            :on-success="handleImported"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <div slot="trigger" @click="handlePushClick($event)">
              <i class="el-icon-plus" />
            </div>
          </el-upload>
          <el-dialog append-to-body :visible.sync="dialogImageVisible">
            <img width="100%" :src="dialogImageUrl">
          </el-dialog>
        </div>
        <div style="display: none;clear: both">{{ formData.businessLicense }}</div>
      </el-form-item>
      <el-form-item label="统一社会信用代码：" class="form-cell" prop="unifiedSocialCreditCode">
        <div class="cell-box">
          <el-input v-model="formData.unifiedSocialCreditCode" placeholder="请输入18位统一社会信用代码" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="纳税人识别号：" class="form-cell" prop="taxpayerIdentificationNumber">
        <div class="cell-box">
          <el-input v-model="formData.taxpayerIdentificationNumber" placeholder="请输入纳税人识别号" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="所属行业：" class="form-cell" prop="industry">
        <div class="cell-box">
          <el-select v-model="formData.industry" placeholder="无" class="cell-select">
            <el-option v-for="item in dict.industry_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="登记机关：" class="form-cell" prop="registrationAuthority">
        <div class="cell-box">
          <el-input v-model="formData.registrationAuthority" placeholder="请输入登记机关" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="法定代表人：" class="form-cell" prop="legalRepresentative">
        <div class="cell-box">
          <el-input v-model="formData.legalRepresentative" placeholder="请输入法定代表人" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="经营状态：" class="form-cell" prop="businessStatus">
        <div class="cell-box">
          <el-select v-model="formData.businessStatus" placeholder="无" class="cell-select">
            <el-option v-for="item in dict.business_status" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="成立日期：" class="form-cell" prop="establishmentDate">
        <div class="cell-box">
          <el-date-picker v-model="formData.establishmentDate" type="date" clearable placeholder="请选择日期" />
        </div>
      </el-form-item>
      <el-form-item label="经营期限（年）：" class="form-cell" prop="operatingPeriod">
        <div class="cell-box">
          <el-input v-model="formData.operatingPeriod" type="number" placeholder="请输入数字" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="审核/年检日期：" class="form-cell" prop="annualInspectionDate">
        <div class="cell-box">
          <el-date-picker v-model="formData.annualInspectionDate" type="date" clearable placeholder="请选择日期" />
        </div>
      </el-form-item>
      <el-form-item label="企业类型：" class="form-cell" prop="enterpriseType">
        <div class="cell-box">
          <el-select v-model="formData.enterpriseType" placeholder="无" class="cell-select">
            <el-option v-for="item in dict.company_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="注册资本（万元）：" class="form-cell" prop="registeredCapital">
        <div class="cell-box">
          <el-input v-model="formData.registeredCapital" type="number" placeholder="请输入数字" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="注册地址：" class="form-cell" required>
        <div class="cell-box">
          <el-form-item prop="registeredAddressProvince" style="margin: 0;display: inline-block;">
            <el-select v-model="formData.registeredAddressProvince" placeholder="省" style="width: 120px" @change="findAreaByCodeAndType(formData.registeredAddressProvince,2, 'cityOpts')">
              <el-option v-for="item in provinceOpts" :key="item.id" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
          <el-select v-model="formData.registeredAddressCity" placeholder="市" style="width: 160px" @change="findAreaByCodeAndType(formData.registeredAddressCity,3, 'countyOpts')">
            <el-option v-for="item in cityOpts" :key="item.id" :label="item.name" :value="item.code" />
          </el-select>
          <el-select v-model="formData.registeredAddressArea" placeholder="区/县" style="width: 160px">
            <el-option v-for="item in countyOpts" :key="item.id" :label="item.name" :value="item.code" />
          </el-select>
        </div>
        <div class="cell-box">
          <el-input v-model="formData.registeredAddressStreet" placeholder="详细地址（例如：和平路北大街106号）" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="经营范围：" class="form-cell" prop="businessScope">
        <div class="cell-box">
          <el-input v-model="formData.businessScope" type="textarea" placeholder="请输入文本内容" maxlength="1000" :autosize="{ minRows: 4, maxRows: 6}" show-word-limit resize="none" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="企业介绍：" class="form-cell" prop="enterpriseIntroduction">
        <div class="cell-box">
          <el-input v-model="formData.enterpriseIntroduction" type="textarea" placeholder="请输入文本内容" maxlength="1000" :autosize="{ minRows: 4, maxRows: 6}" show-word-limit resize="none" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="主营产品介绍：" class="form-cell" prop="mainProductsIntroduction">
        <div class="cell-box">
          <el-input v-model="formData.mainProductsIntroduction" type="textarea" placeholder="请输入文本内容" maxlength="1000" :autosize="{ minRows: 4, maxRows: 6}" show-word-limit resize="none" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="业务范围：" class="form-cell" prop="businessScopeIntroduction">
        <div class="cell-box">
          <el-input v-model="formData.businessScopeIntroduction" type="textarea" placeholder="请输入文本内容" maxlength="1000" :autosize="{ minRows: 4, maxRows: 6}" show-word-limit resize="none" class="cell-input" />
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button @click="cancelView">取消</el-button>
      <el-button type="primary" @click="submitForm()">保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getToken } from '@/utils/auth'
import { HttpReq } from '@/api/common'

export default {
  dicts: ['industry_type', 'supplier_rank', 'company_type', 'business_status'],
  data() {
    return {
      uploadHeaders: { 'Authorization': getToken() },
      imgSrcStart: process.env.VUE_APP_BASE_API,
      dialogImageUrl: '',
      dialogImageVisible: false,
      visible: false,
      title: '编辑客户信息详情',
      customerId: '',
      imgList: [],
      dialogImgUrl: '',
      dialogImgVisible: false,
      provinceOpts: [],
      cityOpts: [],
      countyOpts: [],
      formData: {
        annualInspectionDate: '', // 审核日期
        businessLicense: '', // 营业执照的照片名称
        businessScope: '', // 经营范围
        businessScopeIntroduction: '', // 业务范围介绍
        businessStatus: '', // 经营状态
        enterpriseAddress: '', // 企业地址
        enterpriseContactPerson: '', // 企业联系人
        enterpriseContactPersonPhone: '', // 企业联系人手机号
        enterpriseEmail: '', // 企业邮箱
        enterpriseIntroduction: '', // 企业介绍
        enterpriseName: '', // 企业名称
        enterpriseType: '', // 企业类型
        establishmentDate: '', // 成立日期
        industry: '', // 所属行业
        legalRepresentative: '', // 法定代表人
        mainProductsIntroduction: '', // 主营产品介绍
        operatingPeriod: '', // 经营期限
        registeredAddressArea: '', // 注册地址-区
        registeredAddressCity: '', // 注册地址-市
        registeredAddressProvince: '', // 注册地址-省
        registeredAddressStreet: '', // 注册地址-街道
        registeredCapital: '', // 注册资本
        registrationAuthority: '', // 登记机关
        supplierLevel: '1', // 供应商级别
        taxpayerIdentificationNumber: '', // 纳税人识别号
        unifiedSocialCreditCode: '', // 统一社会信用代码
        sysUserId: null
      },
      rules: {
        enterpriseName: { required: true, message: '请填写企业名称', trigger: 'blur' },
        enterpriseContactPerson: { required: true, message: '请填写企业联系人', trigger: 'blur' },
        enterpriseContactPersonPhone: { required: true, message: '请填写企业联系人手机号', trigger: 'blur' },
        enterpriseAddress: { required: true, message: '请填写企业地址', trigger: 'blur' },
        businessLicense: { required: true, message: '请输上传营业执照', trigger: 'blur' },
        unifiedSocialCreditCode: { required: true, message: '请填写统一社会信用代码', trigger: 'blur' },
        industry: { required: true, message: '请选择所属行业', trigger: 'blur' },
        registeredCapital: { required: true, message: '请填写注册资本', trigger: 'blur' },
        enterpriseIntroduction: { required: true, message: '请填写企业介绍', trigger: 'blur' },
        mainProductsIntroduction: { required: true, message: '请填写主营产品介绍', trigger: 'blur' },
        businessScopeIntroduction: { required: true, message: '请填写业务范围介绍', trigger: 'blur' },
        registeredAddressProvince: { required: true, message: '请填写注册省份', trigger: 'blur' }
      }
    }
  },
  mounted() {
  },
  methods: {
    showView() {
      this.visible = true
    },
    hideView() {
      this.$refs.uploadCom.clearFiles()
      this.$refs.formViewRef.resetFields()
      this.cityOpts = []
      this.countyOpts = []
      this.visible = false
    },
    cancelView() {
      this.hideView()
    },
    submitForm() {
      this.$refs.formViewRef.validate((valid, obj) => {
        if (valid) {
          HttpReq.backstageApi.updateCustomerDetail(this.formData).then((res) => {
            this.$notify({
              title: res.msg,
              type: 'success',
              duration: 2500
            })
            if (res.code === 200) {
              this.cancelView()
              this.$parent.loadData()
            }
          })
        } else {
          this.$message({
            message: '表单信息有误，请核对无误后提交！',
            type: 'error'
          })
        }
      })
    },
    handleProgress(file) {
      if (this.formData.businessLicense.split(';').length >= 2) {
        this.$message({
          message: '超出最大上传数量限制',
          type: 'info'
        })
        return false
      }
    },
    handleExceed() {
      this.$message({
        message: '超出最大上传数量限制',
        type: 'info'
      })
    },
    handleRemoveImg(item) {
      this.imgList.splice(this.imgList.indexOf(item), 1)
      const arr = this.formData.businessLicense.split(';')
      arr.splice(arr.indexOf(item), 1)
      this.formData.businessLicense = arr.join(';')
    },
    handlePushClick(event) {
      if (this.formData.productPic.split(';') >= 2) {
        event.stopPropagation()
        this.$message({
          message: '超出最大上传数量限制',
          type: 'info'
        })
      }
    },
    handleRemove(file, fileList) {
      if (!file.response) {
        return
      }
      HttpReq.backstageApi.deleteBusinessLicense({
        businessLicense: file.response.businessLicense
      }).then((res) => {
        this.$notify({
          title: res.msg,
          type: 'success',
          duration: 2500
        })
        const arr = this.formData.businessLicense.split(';')
        arr.splice(arr.indexOf(file.response.businessLicense), 1)
        this.formData.businessLicense = arr.join(';')
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    handleImported(response, file, fileList) {
      this.$nextTick(() => {
        const arr = this.formData.businessLicense ? this.formData.businessLicense.split(';') : []
        arr.push(response.businessLicense)
        this.formData.businessLicense = arr.join(';')
        this.$notify({
          title: '上传成功！',
          type: 'success',
          duration: 2500
        })
      })
    },
    findAreaByCodeAndType(code, type, optsName) {
      switch (optsName) {
        case 'provinceOpts':
        case 'cityOpts':
          this.formData.registeredAddressCity = null
          this.formData.registeredAddressArea = null
          break
        case 'countyOpts':
          this.formData.registeredAddressArea = null
      }
      this.findAreaQueryOnly(code, type, optsName)
    },
    findAreaQueryOnly(code, type, optsName) {
      HttpReq.backstageApi.findAreaByCodeAndType({
        code, type
      }).then((res) => {
        this[optsName] = res
      })
    },
    loadData(customerId) {
      this.customerId = customerId
      this.findAreaQueryOnly(0, 1, 'provinceOpts')
      HttpReq.backstageApi.queryCustomerDetail({ customerId }).then((res) => {
        if (res.code === 200) {
          this.formData = Object.assign(this.formData, res.data)
          if (this.formData.businessLicense) {
            this.imgList = this.formData.businessLicense.split(';')
          }
          this.findAreaQueryOnly(this.formData.registeredAddressProvince, 2, 'cityOpts')
          this.findAreaQueryOnly(this.formData.registeredAddressCity, 3, 'countyOpts')
          this.showView()
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.cell-box {
  min-width: 120px;
  .cell-input {
    width: 420px;
  }
  .cell-select {
    width: 220px;
  }
  >>>.el-input__inner {
    border: 1px solid rgba(100, 100, 100, 0.1);
    border-bottom: 1px solid rgba(100, 100, 100, 0.2);
    border-radius: 5px;
  }
  >>>.el-input.is-disabled .el-input__inner {
    border-radius: 0;
    border: 0;
    border-bottom: 1px solid rgba(100, 100, 100, 0.4);
    background: white;
    cursor: text;
  }
  >>>.el-input.is-disabled .el-input__icon {
    cursor: text;
  }
  >>>.el-icon-circle-check {
    color: #13ce66;
  }
  //>>>.el-icon-arrow-up:before {
  //  content: '';
  //}
}
</style>
