<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="showModal"
      :close-on-click-modal="false"
      width="800px"
      :title="modalTitle"
    >
      <div>
        <Form
          id="edit-form"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="90"
          inline
        >
          <div>
            <Collapse v-model="infoVal" class="coll-edit coll-search">
              <Panel name="1">
                基本信息
                <p slot="content">
                  <Form-item label="供应商分类" prop="supplier.typeId" class="width-48" placeholder="请选择供应商分类">
                    <el-select
                      v-model="formObj.supplier.typeId"
                      filterable
                      clearable
                      size="small"
                      style="width:100%"
                    >
                      <el-option
                        v-for="item in supplerType"
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                      />
                    </el-select>
                    <input v-model="formObj.supplier.typeId" name="typeId" type="hidden">
                  </Form-item>
                  <Form-item label="供应商名称" prop="supplier.name" class="width-48">
                    <Input v-model="formObj.supplier.name" name="name" placeholder="请输入供应商名称" /></Input>
                  </Form-item>
                  <Form-item label="信用等级" prop="supplier.credit" class="width-48">
                    <autoComplete
                      name="credit"
                      :value="formObj.supplier.credit"
                      placeholder="请输入或选择信用等级"
                      :down-data="creditList"
                      @on-result-change="_creditChange"
                    />
                  </Form-item>
                  <Form-item label="网站" prop="supplier.website" class="width-48">
                    <Input v-model="formObj.supplierDetail.website" name="website" placeholder="请输入网站" /></Input>
                  </Form-item>
                  <Form-item label="省、市、区" class="width-48">
                    <CityCodeCascader
                      :value="cityData"
                      name="customer"
                      @on-result-change="_cascaderResult"
                    />
                    <input name="province" type="hidden">
                    <input name="city" type="hidden">
                    <input name="county" type="hidden">
                  </Form-item>
                  <Form-item label="街道" prop="supplierDetail.address" class="width-48">
                    <Tooltip content="长度为0-50" placement="bottom-start">
                      <Input
                        v-model="formObj.supplierDetail.address"
                        name="address"
                        placeholder="请输入联系街道"
                        style="width:363px "
                        :maxlength="50"
                      /></Input>
                    </Tooltip>
                  </Form-item>
                  <Form-item label="供应/服务范围" prop="supplier.supplyScope" class="width-48">
                    <Input v-model="formObj.supplier.supplyScope" name="supplyScope" placeholder="供应/服务范围" /></Input>
                  </Form-item>
                  <Form-item label="首次列入日期" prop="firstDate" class="width-48">
                    <Date-picker
                      v-model="formObj.supplier.firstDate"
                      type="date"
                      placeholder="首次列入日期"
                      style="width: 100%;"
                      :editable="false"
                      @on-change="_firstDateChange"
                    />
                    <input name="firstDate" type="hidden">
                  </Form-item>
                  <Form-item label="评价表编号" class="width-48" prop="supplier.evaluateCode">
                    <Input v-model="formObj.supplier.evaluateCode" placeholder="请输入评价表编号" name="evaluateCode" /></Input>
                  </Form-item>
                  <Form-item label="评价人员" class="width-48" prop="supplier.evaluatePerson">
                    <Input
                      v-model="formObj.supplier.evaluatePerson"
                      placeholder="请输入评价人员"
                      name="evaluatePerson"
                    /></Input>
                  </Form-item>
                  <Form-item label="审批人" class="width-48" prop="supplier.approver">
                    <Input
                      v-model="formObj.supplier.approver"
                      placeholder="请输入审批人"
                      name="approver"
                    /></Input>
                  </Form-item>
                  <!--<Form-item label="登记人员" class="width-48" prop="supplier.uname" v-show="unameShow">-->
                  <!--<Input placeholder="请输入登记人员" readonly name="uname" v-model="formObj.supplier.uname" ></Input>-->
                  <!--</Form-item>-->
                  <Form-item label="备注" prop="supplierDetail.remark" class="width-48">
                    <Input v-model="formObj.supplierDetail.remark" name="remark" placeholder="请输入备注" /></Input>
                  </Form-item>
                </p>
              </Panel>
              <Panel name="2">
                财务信息
                <p slot="content">
                  <Form-item label="统一社会信用代码" class="width-48" prop="supplier.taxation">
                    <Input v-model="formObj.supplier.taxation" placeholder="请输入统一社会信用代码" name="taxation" /></Input>
                  </Form-item>
                  <Form-item label="开户银行" class="width-48" prop="supplier.bank">
                    <Input v-model="formObj.supplier.bank" placeholder="请输入开户银行" name="bank" /></Input>
                  </Form-item>
                  <Form-item label="账户" class="width-48" prop="supplier.bankAccount">
                    <Input v-model="formObj.supplier.bankAccount" placeholder="请输入账户" name="bankAccount" /></Input>
                  </Form-item>
                  <Form-item label="开票电话" class="width-48" prop="supplier.billTel">
                    <Input v-model="formObj.supplier.billTel" placeholder="请输入开票电话" name="billTel" /></Input>
                  </Form-item>
                </p>
              </Panel>
              <Panel name="3">
                联系方式
                <p slot="content">
                  <Form-item label="主联系人" prop="supplier.contact" class="width-32">
                    <Input v-model="formObj.supplier.contact" name="contact" placeholder="请输入主联系人" /></Input>
                  </Form-item>
                  <Form-item label="联系手机" prop="supplier.mobile" class="width-32">
                    <Input v-model="formObj.supplier.mobile" name="mobile" placeholder="请输入联系手机" /></Input>
                  </Form-item>
                  <Form-item label="固定电话" prop="supplierDetail.phone" class="width-32">
                    <Input v-model="formObj.supplierDetail.phone" name="phone" placeholder="请输入固定电话" /></Input>
                  </Form-item>
                  <Form-item label="邮箱" prop="supplierDetail.email" class="width-32">
                    <Input v-model="formObj.supplierDetail.email" name="email" placeholder="请输入邮箱" /></Input>
                  </Form-item>
                  <Form-item label="传真" prop="supplierDetail.fax" class="width-32">
                    <Input v-model="formObj.supplierDetail.fax" name="fax" placeholder="请输入传真" /></Input>
                  </Form-item>
                  <Form-item label="邮编" prop="supplierDetail.postcode" class="width-32">
                    <Input v-model="formObj.supplierDetail.postcode" name="postcode" placeholder="请输入邮编" /></Input>
                  </Form-item>
                  <Form-item label="法人" prop="supplierDetail.legalPerson" class="width-32">
                    <Input v-model="formObj.supplierDetail.legalPerson" name="legalPerson" placeholder="请输入法人" /></Input>
                  </Form-item>
                  <Form-item label="法人手机" prop="supplierDetail.legalPhone" class="width-32">
                    <Input
                      v-model="formObj.supplierDetail.legalPhone"
                      name="legalPhone"
                      placeholder="请输入法人联系手机"
                    /></Input>
                  </Form-item>
                </p>
              </Panel>
            </Collapse>
          </div>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
/**
 * 添加编辑公司表
 */
import store from 'store2'
import { supplierType, supplier, resDict } from '../../../api'
import global from '../../../api/config'

export default {
  components: {},
  data() {
    const validateName = (rule, value, callback) => {
      // 验证名称
      const reg = /[\u4E00-\u9FA5_a-zA-Z]+$/
      if (value === '' || value === undefined) {
        callback(new Error('企业名称不能为空！'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入中文或英文字符！'))
      } else {
        callback()
      }
    }
    const validateContact = (rule, value, callback) => {
      // 验证联系人
      const reg = /[\u4E00-\u9FA5_a-zA-Z]+$/
      if (value === '' || value === undefined) {
        callback()
      } else if (!reg.test(value)) {
        callback(new Error('请输入中文或英文字符！'))
      } else {
        callback()
      }
    }
    const validateBusno = (rule, value, callback) => {
      // 验证营业执照编号
      const reg = /[A-Za-z0-9]+$/
      if (value === '' || value === undefined) {
        callback()
      } else if (!reg.test(this.formObj.busno)) {
        callback(new Error('请输入英文和数字！'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      // 验证手机号
      const reg = /^((\+?86)|(\(\+86\)))?1\d{10}$/
      if (
        this.formObj.contactWay === '' ||
        this.formObj.contactWay === undefined
      ) {
        callback()
      } else if (!reg.test(this.formObj.contactWay)) {
        callback(new Error('请输入正确格式的手机号！'))
      } else {
        callback()
      }
    }
    const validateDomain = (rule, value, callback) => {
      // 二级域名判定
      const reg = /[A-Za-z0-9_]+$/
      if (value === '') {
        callback()
      } else if (!reg.test(this.formObj.domain)) {
        //
        callback(new Error('只能输入字母、数字、下划线！'))
      } else {
        callback()
      }
    }
    return {
      isLogo: false, // 是否显示上传logo
      id: '',
      modalTitle: '添加供应商信息',
      formObj: {
        supplier: {
          contact: '',
          credit: '',
          mobile: '',
          name: '',
          rank: '',
          status: '',
          type: '',
          uid: '',
          id: '',
          typeId: '',
          bankAccount: '',
          taxation: '',
          bank: '',
          billTel: '',
          firstDate: '',
          evaluateCode: '',
          supplyScope: '',
          evaluatePerson: '',
          uname: '',
          approver: ''
        },
        supplierDetail: {
          address: '',
          email: '',
          fax: '',
          legalPerson: '',
          legalPhone: '',
          phone: '',
          postcode: '',
          remark: '',
          supplierId: '',
          website: '',
          id: '',
          street: '',
          province: '',
          county: '',
          city: ''
        }
      },
      typeList: [
        { value: 1, label: '第一方企业' },
        { value: 2, label: '第三方检测' },
        { value: 3, label: '其它' }
      ],
      supplerType: [], // 供应商分类
      statusList: [{ value: 0, label: '禁用' }, { value: 1, label: '正常' }],
      ruleValidate: {
        busno: [{ validator: validateBusno, trigger: 'blur' }],
        contactWay: [{ validator: validatePhone, trigger: 'blur' }],
        name: [{ required: true, validator: validateName, trigger: 'blur' }],
        domain: [{ validator: validateDomain, trigger: 'blur' }],
        contact: [{ validator: validateContact, trigger: 'blur' }],
        sort: [
          {
            required: true,
            message: '排序不能为空',
            trigger: 'blur',
            type: 'number'
          }
        ]
      },
      showModal: false,
      uploadList: [],
      action: '',
      dataObj: {
        file: '',
        companyId: ''
      },
      imgUri: '',
      cityData: [],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ],
      showLogo: false,
      businessList: [],
      accept: '.jpg,.jpeg,.png,.JPEG,.PNG,.JPG'
    }
  },
  mounted() {
    this._dicSearch()
    this._supplerType()
  },
  methods: {
    // 查询字典
    _dicSearch: async function() {
      const result = await resDict.getItem('业务类型')
      this.businessList = result
    },

    _supplerType: async function() {
      const result = await supplierType.getList({})
      this.supplerType = result
    },
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '保存':
          this._ok()
          break
      }
    },
    _cascaderResult(name, data) {
      if (data.selectedData.length > 0) {
        const provinceCode = data.selectedData[0]
          ? data.selectedData[0].code
          : ''
        const cityCode = data.selectedData[1] ? data.selectedData[1].code : ''
        const areaCode = data.selectedData[2] ? data.selectedData[2].code : ''

        this.formObj.provinceCode = provinceCode
        this.formObj.cityCode = cityCode
        this.formObj.areaCode = areaCode
        this.cityData = [provinceCode, cityCode, areaCode]
      } else {
        this.formObj.provinceCode = ''
        this.formObj.cityCode = ''
        this.formObj.areaCode = ''
        this.cityData = []
      }
    },
    _selectType(data) {
      this.formObj.type = data
    },
    _selectNotifyWechat(data) {
      this.formObj.notifyWechat = data
    },
    _selectStatus(data) {
      this.formObj.status = data
    },
    _resultChange(result, msg) {
      if (result) {
        this.showModal = false
        this.$message.success(msg)
        this.$emit('on-result-change')
      }
      this.$refs.footerModal._hideLoading()
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          this._save(data)
        } else {
          this.$refs.footerModal._hideLoading()
          this.$message.error('表单验证失败!')
        }
      })
    },
    _save: async function(data) {
      if (this.$string(this.id).isEmpty()) {
        const result = await supplier.add(data)
        this._resultChange(result, '添加成功!')
      } else {
        const result = await supplier.edit({ id: this.formObj.id, obj: data })
        this._resultChange(result, '编辑成功!')
      }
    },
    _cancel() {
      this.$refs.footerModal._hideLoading()
      this.showModal = false
    },
    _open(formObj) {
      this.showModal = true
      this.$nextTick(() => {
        this.$refs.footerModal._hideLoading()
        this.$refs.formObj.resetFields()
        this.cityData = []
        if (this.$string(formObj).isEmpty()) {
          this.id = ''
          this.modalTitle = '添加企业'
          this.isLogo = false
        } else {
          this.id = formObj.id
          this.formObj = formObj
          if (formObj.provinceCode) {
            this.cityData = [
              formObj.provinceCode,
              formObj.cityCode,
              formObj.areaCode
            ]
          }
          this.modalTitle = '编辑企业'
          this.isLogo = true
          this.action = global.baseURL + '/base/v1/company/logo_' + formObj.id
          if (formObj.logo) {
            // 有logo
            this.showLogo = true
            this.imgUri =
              global.baseURL + '/base/v1/company/logo?key=' + formObj.logo
          } else {
            // 无logo
            this.showLogo = false
          }
        }
      })
    },
    _beupload(file) {
      this.dataObj.file = file.name
      this.dataObj.companyId = this.id
    },
    _handelprogress() {
      this.$Spin.show({
        render: h => {
          return h('div', [
            h('Icon', {
              class: 'upload-spin-icon-load',
              props: {
                type: 'load-c',
                size: 18
              }
            }),
            h('div', '图片上传中，请稍后...')
          ])
        }
      })
    },
    _handelsuccess(response, file, fileList) {
      // 上传成功
      this.$Spin.hide()
      if (response.success) {
        this.$message.success('上传成功！')
        this.imgUri =
          global.baseURL + '/base/v1/company/logo?key=' + response.data
        store.set('logo', response.data)
        this.showLogo = true
      } else {
        this.$message.error('上传失败！')
        this.showLogo = false
      }
    },
    _handleFormatError(file) {
      this.$Notice.warning({
        title: '图片格式不正确',
        desc: '图片 ' + file.name + ' 格式不正确，请上传格式为jpg,png的图片！'
      })
    },
    _handleMaxSize(file) {
      this.$Notice.warning({
        title: '图片过大',
        desc: '图片  ' + file.name + ' 过大, 图片大小要＜1M.'
      })
    }
  }
}
</script>
<style scoped>
.logo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}

.logo-upload-list img {
  width: 100%;
  height: 100%;
}
</style>
