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

        <a-form-item label="企业名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'companyName', validatorRules.companyName]" :maxlength="100" placeholder="请输入企业名称"></a-input>
        </a-form-item>
          
        <a-form-item label="税号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'dutyParagraph', validatorRules.dutyParagraph]" :maxlength="30" placeholder="请输入税号"></a-input>
        </a-form-item>

        <a-form-item label="营业执照" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <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>
        </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]" :maxlength="100" placeholder="请输入所在地区-详细地址"></a-input>
        </a-form-item>
          
        <a-form-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'contactPerson', validatorRules.contactPerson]" :maxlength="30" placeholder="请输入联系人"></a-input>
        </a-form-item>
          
        <a-form-item label="手机号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'mobilePhone', validatorRules.mobilePhone]" :maxlength="11" placeholder="请输入手机号"></a-input>
        </a-form-item>
          
        <a-form-item label="固定电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'phone', validatorRules.phone]" :maxlength="15" 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 data1 from '../../tools/area.json'
  import { duplicateCheck } from '@/api/api'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'

  export default {
    name: "HlgCompanyModal",
    components: { 
    },
    data () {
      return {
        disableSubmit:false,
        arr:[],  //存放回显默认省市区code
        provArray: [], //存放省
        cityArray: [],   //存放市
        countryArray:[],  //存放区
        options: [{
          value: '',
          label: '',
          isLeaf: false
        }],
        form: this.$form.createForm(this),
        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 },
        },

        picUrl: '',
        uploadLoading: false,
        confirmLoading: false,
        validatorRules:{
        companyName:{rules: [{ required: true, message: '请输入企业名称!' },{
            validator: this.validateCompanyAbbreviation
          }]},
        dutyParagraph:{rules: [{ required: true, message: '请输入税号!' },{
            validator: this.validateDutyParagraphAbbreviation
          }]},
        businessLicense:{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:{},
        mobilePhone:{ rules: [{ validator: this.validatePhone }] },
        phone:{rules: [{ validator: this.validatePhoneAbbreviation }]},
        },
        url: {
          add: "/hlgcompany/hlgCompany/add",
          edit: "/hlgcompany/hlgCompany/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.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'companyName','dutyParagraph','businessLicense','provinceCode','cityCode','countryCode','provinceCityCountry','address','contactPerson','mobilePhone','phone'))
        })
        //回显省市区
        this.arr=[]
        this.arr.push(String(this.model.provinceCode))
        this.arr.push(String(this.model.cityCode))
        this.arr.push(String(this.model.countryCode))
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        if(this.arr.length!=3||this.arr[0]=="undefined"){
          this.$message.warning("请选择所在地区");
          return
        }
        if (this.picUrl == '') {
          this.$message.warning('请上传营业执照！')
          return
        }
        const that = this;
        // 触发表单验证
        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);
            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','dutyParagraph','businessLicense','provinceCode','cityCode','countryCode','provinceCityCountry','address','contactPerson','mobilePhone','phone','companyCode'))
      },

      //校验企业名称重复
      validateCompanyAbbreviation(rule, value, callback) {
        var params = {
          tableName: 'hlg_company',
          fieldName: 'company_name',
          fieldVal: value,
          dataId: this.model.id
        }
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback('企业名称已存在!')
          }
        })

      },


      //校验税号重复+校验字符串格式
      validateDutyParagraphAbbreviation(rule, value, callback) {
        var params = {
          tableName: 'hlg_company',
          fieldName: 'duty_paragraph',
          fieldVal: value,
          dataId: this.model.id
        }
        duplicateCheck(params).then((res) => {
          if (res.success) {
            var re =  /^[0-9a-zA-Z]*$/;  //判断字符串是否为数字和字母组合
            if (re.test(value))
            {
              callback()
            }else{
              callback('只能填写数字或字母!')
            }
          } else {
            callback('该税号已存在!')
          }
        })

      },


      //校验固话只能为数字
      validatePhoneAbbreviation(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (new RegExp(/^[0-9]*$/).test(value)) {
            callback()
          } else {
            callback('请输入数字!')
          }
        }

      },


      //校验手机号
      validatePhone(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (new RegExp(/^1[0-9][0-9]\d{8}$/).test(value)) {
            callback()
          } else {
            callback('请输入正确格式的手机号码!')
          }
        }
      },

      //省市区改变
      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 })
          }
        })

      },
      //已认证的禁用
      disable(){
        return this.model.id;
      },
      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
      },
    }
  }
</script>
<style>
  .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;
  }
  .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;
  }
</style>