<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="[ 'platformName', validatorRules.platformName]" placeholder="请输入平台名称"></a-input>
        </a-form-item>

        <a-form-item label="企业名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'enterpriseName', validatorRules.enterpriseName]" placeholder="请输入企业名称"></a-input>
        </a-form-item>

        <a-form-item label="企业税号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'dutyParagraph', validatorRules.dutyParagraph]" 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]" 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-item label="业务归属" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select type="list" v-decorator="['businessBelongId',validatorRules.businessBelongId]" :trigger-change="true" @change="changeBelong"
                    :options="selectOption.options" placeholder="选择业务归属" style="width: 100%" :disabled="isDisabled"/>
        </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,putAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import axios from 'axios'
  import data1 from '../../tools/area.json'
  import { duplicateCheck } from '@/api/api'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  // 引入搜索服务商弹出框的组件
  const findList = (params) => putAction('/platmanager/hwPlatform/applicationSubList', params)

  export default {
    name: 'HwPlatformModal',
    components: {
      JDate,
      JDictSelectTag
    },
    data() {
      return {
        selectOption: {
          options: [

          ]
        },
        isDisabled:false,
        disableSubmit:false,
        arr:[],  //存放回显默认省市区code
        provArray: [], //存放省
        cityArray: [],   //存放市
        countryArray:[],  //存放区
        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 }
        },
        options: [{
          value: '',
          label: '',
          isLeaf: false
        }],
        picUrl: '',
        uploadLoading: false,
        confirmLoading: false,
        validatorRules: {
          platformName: { rules: [{ required: true, message: '请输入平台名称!' }, {
              validator: this.validateCompanyAbbreviation
            }] },
          dutyParagraph:{ rules: [{ required: true, message: '请输入企业税号!' }] },
          enterpriseName: { rules: [{ required: true, message: '请输入企业名称!' }] },
          provinceCode: { rules: [{ required: true, message: '请输入所在地区-省Code!' }] },
          cityCode: { rules: [{ required: true, message: '请输入所在地区-市Code!' }] },
          countryCode: { rules: [{ required: true, message: '请输入所在地区-区Code!' }] },
          provinceCityCountry: {},
          address: {},
          contactPerson: {},
          contactPhone: { rules: [{ validator: this.validatePhone }] },
          isDataShare: { rules: [{ required: true, message: '请输入是否数据共享' }] },
          startDate: { rules: [{ required: true, message: '请输入开始时间!' }] },
          endDate: { rules: [{ required: true, message: '请输入结束时间!' }] },
          status: { rules: [{ required: true, message: '请输入状态' }] },
          businessBelongId:{ rules: [{ required: true, message: '请选择业务归属' }] }
        },
        url: {
          add: '/platmanager/hwPlatform/add',
          edit: '/platmanager/hwPlatform/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.isDisabled=false;
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.querySubcontratorList()
        if (record.hasOwnProperty('id')) {
          this.picUrl = 'Has no pic url yet'
        }
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'id','platformName', 'enterpriseName', 'provinceCode','businessBelongId','businessBelong','isShare', 'cityCode', 'countryCode', 'provinceCityCountry', 'address', 'contactPerson', 'contactPhone', 'isDataShare', 'startDate', 'endDate', 'status','dutyParagraph','businessLicense'))
          this.form.setFieldsValue({ status:this.model.status!=null? String(this.model.status):''})
        })
        //回显省市区
        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() {
        console.log(111111,this.arr)
        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, 'id','platformName', 'enterpriseName', 'provinceCode', 'cityCode', 'countryCode', 'provinceCityCountry', 'address', 'contactPerson', 'contactPhone', 'isDataShare', 'startDate', 'endDate', 'status','dutyParagraph','businessLicense'))
      },
      //校验平台名称重复
      validateCompanyAbbreviation(rule, value, callback) {
        var params = {
          tableName: 'hw_platform',
          fieldName: 'platform_name',
          fieldVal: value,
          dataId: this.model.id
        }
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback('平台名称已存在!')
          }
        })

      },
      //校验手机号
      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('请输入正确格式的手机号码!')
          }
        }
      },

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

      changeBelong(val){
        this.model.businessBelongId=val
        for (let i = 0; i < this.selectOption.options.length ; i++) {
          if(val==this.selectOption.options[i].value){
            this.model.businessBelong=this.selectOption.options[i].label
          }
        }
      },

      //查询慧盈配置
      querySubcontratorList() {
        findList({}).then((res) => {
          if (res.success) {
            this.selectOption.options=[]
            this.form.setFieldsValue({businessBelongId:null})
            for(let i = 0;i<res.result.length;i++){
              if(res.result[i].cpType==2){
                this.selectOption.options.push({label: res.result[i].abbreviation, value:res.result[i].id })
                if(this.model.businessBelongId){
                  this.isDisabled=true
                  this.$nextTick(() => {
                    this.form.setFieldsValue({ businessBelongId:this.model.businessBelongId})
                  })
                }
              }
            }
          }
        })
      },




    }
  }
</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>