<template>
  <a-modal
    :title='title'
    :width='width'
    :bodyStyle='bodyStyle'
    @ok='handleOk'
    @cancel='handleCancel'
    :maskClosable='false'
    :visible='visible'
    :footer='null'
    cancelText="关闭">
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>

        <a-form-item label='企业名称' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
          <a-input v-decorator="[ 'companyName', validatorRules.companyName]" placeholder='请输入企业名称'
                   :disabled='disable()'></a-input>
        </a-form-item>
        <a-form-item label='税号' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
          <a-input v-decorator="[ 'dutyParagraph', validatorRules.dutyParagraph]" placeholder='请输入税号'
                   :disabled='disable()'></a-input>
        </a-form-item>
        <a-form-item label='营业执照' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
          <template v-if='disable()'>
            <img :src='getAvatarView()' :preview='getAvatarView()' alt='营业执照' style='height:104px;max-width:300px' />
          </template>
          <template v-else>
            <a-upload
              listType='picture-card'
              class='avatar-uploader'
              :showUploadList='false'
              :action='uploadAction'
              :data="{'isup':1,'bizPath':bizPath}"
              :headers='headers'
              :beforeUpload='beforeUpload'
              @change='handleChange'
            >
              <img v-if='picUrl' :src='getAvatarView()' alt='营业执照' style='height:104px;max-width:300px' />
              <div v-else>
                <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
                <div class='ant-upload-text'>上传</div>
              </div>
            </a-upload>
          </template>
        </a-form-item>
        <a-form-item label='企业简称' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
          <a-input v-decorator="[ 'companyAbbreviation', validatorRules.companyAbbreviation]"
                   placeholder='请输入企业简称'></a-input>
        </a-form-item>

        <a-form-item label='所属行业' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
          <j-dict-select-tag type='list' v-decorator="['tradeType',validatorRules.tradeType]" :trigger-change='true'
                             dictCode='trade_type' placeholder='请选择所属行业' style='width: 100%' />
        </a-form-item>

        <a-form-item label='所在地区' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
          <a-cascader :options='options' :value='arr' @change='onChange' placeholder='请选择所在地区'
                      changeOnSelect />
        </a-form-item>
        <a-form-item label='详细地址' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-input v-decorator="[ 'address', validatorRules.address]" placeholder='请输入详细地址'></a-input>
        </a-form-item>
        <a-form-item label='联系人' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-input v-decorator="[ 'contactPerson', validatorRules.contactPerson]" placeholder='请输入联系人'></a-input>
        </a-form-item>
        <a-form-item label='联系电话' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-input v-decorator="[ 'contactPhone', validatorRules.contactPhone]" placeholder='请输入联系电话'></a-input>
        </a-form-item>

      </a-form>
    </a-spin>
    <div class='drawer-bootom-button' v-show='!disableSubmit'>
      <a-button class='ant-btn' @click='handleCancel'>关闭</a-button>
      <a-button class='ant-btn ant-btn-primary' style='margin-left: 8px' @click='handleOk'>确定</a-button>
    </div>

  </a-modal>
</template>

<script>

import { httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import Vue from 'vue'
import JDate from '@/components/jeecg/JDate'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import data1 from '../../tools/area.json'
import { duplicateCheck } from '@/api/api'


export default {
  name: 'HwPlatformCompanyModal',
  components: {
    JDate
  },
  data() {
    return {
      disableSubmit: false,
      arr: [],  //存放回显默认省市区code
      provArray: [], //存放省
      cityArray: [],   //存放市
      countryArray: [],  //存放区
      options: [{
        value: '',
        label: '',
        isLeaf: false
      }],
      companyId: '',
      form: this.$form.createForm(this),
      picUrl: '',
      title: '操作',
      width: 800,
      bodyStyle: {
        paddingTop: '20px',
        paddingBottom: '50px',
        height: (window.innerHeight * 0.62) + 'px',
        'overflow-y': 'auto'
      },
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      uploadLoading: false,
      confirmLoading: false,
      headers: {},
      selectedDepartKeys: [], //保存用户选择服务商id
      checkedDepartKeys: [],
      validatorRules: {
        companyName: {
          rules: [
            { required: true, message: '请输入企业名称!' },
            {
              validator: this.validateCompanyName
            }]
        },
        companyAbbreviation: {
          rules: [{ required: true, message: '请输入企业简称!' }, {
            validator: this.validateCompanyAbbreviation
          }]
        },
        tradeType: { rules: [{ required: true, message: '请输入所属行业' }] },
        provinceCode: { rules: [{ required: true, message: '请输入所在地区-省Code!' }] },
        cityCode: { rules: [{ required: true, message: '请输入所在地区-市Code!' }] },
        countryCode: { rules: [{ required: true, message: '请输入所在地区-区Code!' }] },
        provinceCityCountry: { rules: [{ required: true, message: '请输入省市区全称!' }] },
        address: {},
        contactPerson: {},
        contactPhone: { rules: [{ validator: this.validatePhone }] },
        subcontractorId: { rules: [{ required: true, message: '请选择服务商!' }] },
        dutyParagraph: {
          rules: [{ required: true, message: '请输入税号!' }, {
            validator: this.validateDutyParagraph
          }]
        },
        businessLicense: { rules: [{ required: true, message: '请上传营业执照!' }] }
      },
      url: {
        add: '/saasmanager/hwPlatformCompany/add',
        edit: '/saasmanager/hwPlatformCompany/edit',
        fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        imgerver: window._CONFIG['imgDomainOssURL']
      }

    }
  },
  props: {
    /*这个属性用于控制文件上传的业务路径*/
    bizPath: {
      type: String,
      required: false,
      default: '/hpwork/hwcompany'
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }
    //省市区options完全拼接
    for (var i = 0; i < data1.length; i++) {
      this.cityArray = []
      for (let j = 0; j < data1[i].cityList.length; j++) {
        this.countryArray = []
        for (let k = 0; k < data1[i].cityList[j].areaList.length; k++) {
          var country = {
            value: data1[i].cityList[j].areaList[k].code,
            label: data1[i].cityList[j].areaList[k].name
          }
          this.countryArray.push(country)
        }
        var city = {
          value: data1[i].cityList[j].code,
          label: data1[i].cityList[j].name,
          children: this.countryArray
        }
        this.cityArray.push(city)
      }
      var prov = {
        value: data1[i].code,
        label: data1[i].name,
        children: this.cityArray
      }
      this.provArray.push(prov)
      this.options = this.provArray
    }
  },
  computed: {
    uploadAction: function() {
      return this.url.fileUpload
    }
  },
  methods: {
    add() {
      this.picUrl = ''
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      if (record.hasOwnProperty('id')) {
        this.picUrl = 'Has no pic url yet'
      }
      this.companyId = record.id
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'companyName', 'subcontractorName', 'tradeType', 'companyAbbreviation', 'provinceCode', 'cityCode', 'countryCode', 'provinceCityCountry', 'address', 'contactPerson', 'contactPhone', 'businessLicense', 'subcontractorId', 'dutyParagraph'))
        this.form.setFieldsValue({ subcontractorName: this.model.subcontractorName })
        this.form.setFieldsValue({ tradeType: this.model.tradeType != null ? String(this.model.tradeType) : '' })
      })
      this.visible = true
      //回显省市区
      this.arr = []
      this.arr.push(String(this.model.provinceCode))
      this.arr.push(String(this.model.cityCode))
      this.arr.push(String(this.model.countryCode))
      this.selectedDepartKeys = []
      this.checkedDepartKeys = []
      if (this.model.subcontractorId) {
        this.checkedDepartKeys.push(this.model.subcontractorId)
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.selectedDepartKeys = []
      this.checkedDepartKeys = []
    },
    beforeUpload: function(file) {
      var fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请上传图片')
        return false
      }
      //TODO 验证文件大小
    },
    handleChange(info) {
      this.picUrl = ''
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        var response = info.file.response
        this.uploadLoading = false
        console.log(response)
        if (response.success) {
          this.model.businessLicense = response.message
          this.picUrl = 'Has no pic url yet'
        } else {
          this.$message.warning(response.message)
        }
      }
    },
    getAvatarView() {
      return this.url.imgerver + this.model.businessLicense
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (new RegExp(/^1[3|4|5|7|8][0-9]\d{8}$/).test(value)) {
          callback()
        } else {
          callback('请输入正确格式的手机号码!')
        }
      }
    },
    handleOk() {
      const that = this
      if (that.arr.length != 3 || that.arr[0] == 'undefined') {
        that.$message.warning('请选择省市区')
        return
      }
      if (that.picUrl == '') {
        that.$message.warning('请上传营业执照！')
        return
      }
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          if (this.selectedDepartKeys[0]) {
            formData.subcontractorId = this.selectedDepartKeys[0]
          }
          console.log('表单提交数据', formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }

      })
    },
    handleCancel() {
      this.close()
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, 'companyName', 'companyCode', 'tradeType', 'subcontractorName', 'companyAbbreviation', 'provinceCode', 'cityCode', 'countryCode', 'provinceCityCountry', 'address', 'contactPerson', 'contactPhone', 'businessLicense', 'subcontractorId', 'dutyParagraph'))
    },
    //省市区改变
    onChange(value, label) {
      this.arr = value
      this.model.provinceCode = value[0]
      this.model.cityCode = value[1]
      this.model.countryCode = value[2]
      this.$nextTick(() => {
        this.form.setFieldsValue({ provinceCode: this.model.provinceCode })
        this.form.setFieldsValue({ cityCode: this.model.cityCode })
        this.form.setFieldsValue({ countryCode: this.model.countryCode })
        if (label.length == 3) {
          this.model.provinceCityCountry = label[0].label + '-' + label[1].label + '-' + label[2].label
          this.form.setFieldsValue({ provinceCityCountry: this.model.provinceCityCountry })
        }
      })

    },
    validateCompanyName(rule, value, callback) {
      var params = {
        tableName: 'hw_platform_company',
        fieldName: 'company_name',
        fieldVal: value,
        dataId: this.companyId
      }
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback('企业已存在!')
        }
      })
    },
    validateDutyParagraph(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (new RegExp(/^[0-9a-zA-Z]*$/g).test(value)) {
          var params = {
            tableName: 'hw_platform_company',
            fieldName: 'duty_paragraph',
            fieldVal: value,
            dataId: this.companyId
          }
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback('税号已存在!')
            }
          })
        } else {
          callback('请输入正确格式的税号!')
        }
      }
    },
    validateCompanyAbbreviation(rule, value, callback) {
      var params = {
        tableName: 'hw_platform_company',
        fieldName: 'company_abbreviation',
        fieldVal: value,
        dataId: this.companyId
      }
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback('企业简称已存在!')
        }
      })

    },
    //已认证的禁用
    disable() {
      return this.model.authenticationStatus == '2'
    }

  }
}
</script>

<style lang='less' scoped>

.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}

.ant-upload-select-picture-card i {
  font-size: 49px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>