<template>
  <div class="batchChangeAddress" style='width:900px;' data-key="BATCH_ADDRESS">
    <Form
      ref="formValidate"
      class="form"
      :model="formValidate"
      :rules="ruleValidate"
      label-position="right"
      :label-width="80"
      :inline="inline"
    >
        <Row>
          <Col span="8" >
          <FormItem
            label="姓名"
            prop="name"
          >
            <Input v-model="formValidate.name" ></Input>
          </FormItem>
          </Col>
          <Col span="8" >
          <FormItem
            label="手机号"
            prop="mobile"
          >
            <Input v-model="formValidate.mobile" ></Input>
          </FormItem>
          </Col>
          <Col span="8" >
          <FormItem
            label="电话"
            prop="phone"
          >
            <Input v-model="formValidate.phone" ></Input>
          </FormItem>
          </Col>
        </Row>
    </Form>
    <Form
        ref="formValidate"
        class="form"
        :model="formValidate"
        :rules="ruleValidate"
        label-position="right"
        :label-width="80"
        :inline="inline"
      >
        <Row>
          <Col span="8">
            <FormItem
              label="收件人省"
              prop="province"
            >
              <Select
                v-model="formValidate.province"
                @on-change="selectProvinceBtn"
              >
                <Option
                  v-for="optionsItem in provinceList"
                  :key="optionsItem.value"
                  :value="optionsItem.label"
                >
                  {{ optionsItem.label }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
          <FormItem
            label="收件人市"
            prop="city"
          >
            <Select
              v-model="formValidate.city"
              @on-change="selectCityBtn"
            >
              <Option
                v-for="optionsItem in cityList"
                :key="optionsItem.value"
                :value="optionsItem.label"
              >
                {{ optionsItem.label }}
              </Option>
            </Select>
          </FormItem>
          </Col>
          <Col span="8">
          <FormItem
            label="收件人区"
            prop="area"
          >
            <Select
              v-model="formValidate.area"
              @on-change="selectAreaBtn"
            >
              <Option
                v-for="optionsItem in areaList"
                :key="optionsItem.value"
                :value="optionsItem.label"
              >
                {{ optionsItem.label }}
              </Option>
            </Select>
          </FormItem>
          </Col>
        </Row>
    </Form>
    <Form
        ref="formValidate"
        class="form"
        :model="formValidate"
        :rules="ruleValidate"
        label-position="right"
        :label-width="80"
        :inline="inline"
      >
        <Row>
          <!-- v-if='PLATFORM=="57"' -->
          <Col span="8">
            <FormItem
              label="收件人街道"
              prop="town"
            >
              <Input v-model="formValidate.town" ></Input>
            </FormItem>
          </Col>
          <Col span="16" >
          <FormItem
            label="详细地址"
            prop="detailAddress"
          >
            <Input v-model="formValidate.detailAddress" ></Input>
          </FormItem>
          </Col>
          <Col span="8" >
          <FormItem label="邮编">
            <Input v-model="formValidate.postCode" ></Input>
          </FormItem>
          </Col>
          <Col span="8" >
            <FormItem label="收货人国家">
              <Input v-model="formValidate.receiveContry" ></Input>
            </FormItem>
          </Col>
        </Row>
    </Form>
    <Form 
        ref="formValidate"
        class="form"
        :model="formValidate"
        :rules="ruleValidate"
        label-position="right"
        :label-width="80"
        :inline="inline">
        <Row>
          <Col span="16" v-if="IS_OVERSEAS">
          <FormItem label="清关信息" prop="customs_clearance_info">
            <Select
              v-model="formValidate.customs_clearance_type"
              placeholder="请选择证件类型"
              style='width: 30%'
              @on-change="selectclearancetypeBtn"
            >
              <Option
                v-for="optionsItem in clearancetypeList"
                :key="optionsItem.value"
                :value="optionsItem.value"
              >
                {{ optionsItem.label }}
              </Option>
            </Select>
            <Input style='width: 50%' placeholder="请填写证件号码" v-model="formValidate.customs_clearance_info"></Input>
            <!-- <p v-if="!isValidIdNumber && formValidate.customs_clearance_info">身份证号码不正确</p> -->
          </FormItem>
          </Col>
        </Row>
      </Form>
    <Form
        class="form"
        :model="formValidate"
        label-position="top"
        :inline="inline"
        style="padding-left: 20px; margin-top: 20px"
      >
        <FormItem label="智能识别">
          <Input
            v-model="formValidate.desc"
            class="text1"
            type="textarea"
            placeholder="粘贴地址信息后回车,自动识别姓名、电话和地址"
            @on-keydown="searchsmart"
          ></Input>
        </FormItem>
    </Form>
    <footer style="display: flex; justify-content: flex-end; margin-top: 16px">
      <Button
        type="fcdefault"
        @click="cancel()"
      >
        取消
      </Button>
      <Button
        type="posdefault"
        style="margin-left: 8px;"
        @click="submit()"
      >
        确定
      </Button>
    </footer>
  </div>
</template>

<script>
  // import AddressParse from 'address-parse';
  import AddressParse from '../../../static/@address-parse/dist/parse/index';
  
  const R3 = window.R3;
  const { network, urlSearchParams, store } = R3;
  export default {
    name: 'batchChangeAddress',
    props: {
      selectRowData: { // 获取选择行的数据
        type: Array,
        default: () => []
      },
      idArray: {// 获取ID用于多选
        type: [Array, Object],
        default: () => {
        }
      },
    },
    created() {
        this.getProvinceList()
        for(let i=0;i<this.selectRowData.length;i++){
          // 是否海外，格式: {refobjval: 1, val: "是"}
          if(this.selectRowData[i].IS_OVERSEAS.refobjval == '1'){
            this.IS_OVERSEAS = true;
            break;
          }
        }
    },
    data() {
      const CrdtNoValidar=(rule,value,callback)=>{
               if(value && this.formValidate.customs_clearance_type == '1'){
                  if(value=="无"){
                    callback();
                      return
                    }
                    let reg18=/^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dXx]$/;
                    let reg15=/^[1-9]\d{7}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$/;
                    if(reg18.test(value)||reg15.test(value)){
                      callback()
                    }else{
                      callback(new Error("请输入有效的身份证号码！"))
                    }
               }else{
                callback()
               }
         };
        const validateProvince = (rule, value, callback) => {
            if (value === '') {
            callback(new Error('收件人省不能为空'));
            } else {
            callback();
            }
        };
        const validateCity = (rule, value, callback) => {
            if (value === '') {
            callback(new Error('收件人市不能为空'));
            } else {
            callback();
            }
        };
        // 收货人地址校验：不能为纯数字
        const validateReceiveAddress = (rule, value, callback) => {
            const rAddress = this.formValidate.detailAddress;
            if (!rAddress) {
            return callback(new Error('收货人地址不能为空!'));
            }
            // console.log(/^(?=.*?[\u4E00-\u9FA5])[\d\u4E00-\u9FA5]{1,}/.test(rAddress))
            // if (/^(?=.*?[\u4E00-\u9FA5])[\d\u4E00-\u9FA5]{1,}/.test(rAddress)) {
            //   return callback();
            // }
            return callback();
            // return callback(new Error('收货人地址格式不正确!'));
        };
      return {
        inline: false,
        clearancetypeList: [
          {
            label: '身份证',
            value: '1'
          },
          {
            label: '军官证',
            value: '2'
          },
          {
            label: '护照',
            value: '3'
          },
          {
            label: '其他',
            value: '4'
          },
        ],
        IS_OVERSEAS: false,
        provinceList: [],
        cityList: [],
        areaList: [],
        formValidate: {
          name: '',
          mobile: '',
          phone: '',
          province: '',
          city: '',
          area: '',
          town: '',
          provinceId: '',
          cityId: '',
          areaId: '',
          detailAddress: '',
          postCode: '',
          desc: '',
          buyNickname: '',
        },
        ruleValidate: {
          name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
          province: [{ required: true, validator: validateProvince, trigger: 'change' }],
          city: [{ required: true, validator: validateCity, trigger: 'change' }],
          customs_clearance_info:[{required:true,message:'请输入证件号码',trigger:'blur'}],
          detailAddress: [{
            validator: validateReceiveAddress,
            required: true,
            trigger: 'blur'
          }],
        },
      };
    },
    methods: {
        selectclearancetypeBtn() {
          this.formValidate.customs_clearance_info = ''
        },
        // 获取省市区
        getProvinceList() {
            // 省
            let virtual = {
            table: 'T_OMSREGION_PROVINCE',
            isdroplistsearch: true,
            range: 1000,
            startindex: 0,
            };
            network.post('/p/cs/list/query', virtual).then((res) => {
            this.provinceList = res.data.rows.map((item) => ({
                value: item.ID.val,
                label: item.REGIONNAME.val,
            }));
            // 获取省列表
            this.selectProvince(this.formValidate.province);
            });
        },
        // 选择省份
      selectProvince(val) {
        let data = this.provinceList.find((item) => item.label == val); //在省列表中找对应的省id
        if(data){
          // 市
          let virtual = {
            table: 'T_OMSREGION_CITY',
            isdroplistsearch: true,
            range: 1000,
            startindex: 0,
            fixedcolumns: { PARENTID: [`=${data.value}`] },
          };
          network.post('/p/cs/list/query', virtual).then((res) => {
            this.cityList = res.data.rows.map((item) => ({
              value: item.ID.val,
              label: item.REGIONNAME.val,
            }));
            // 获取市列表
            if (this.smartCity) { //智能识别市就获取市ID
              this.getCityNum(this.smartCity);
            } else {//识别不到就通过默认的选择
              this.selectCity(this.formValidate.city);
            }
          });
        }
        
      },
      // 选择市
      selectCity(val) {
        let data = this.cityList.find((item) => item.label == val);//在市列表中找对应的市id
        // 市
        if (data) {
          let virtual = {
            table: 'T_OMSREGION_AREA',
            isdroplistsearch: true,
            range: 1000,
            startindex: 0,
            fixedcolumns: { PARENTID: [`=${data.value}`] },
          };
          network.post('/p/cs/list/query', virtual).then((res) => {
            this.areaList = res.data.rows.map((item) => ({
              value: item.ID.val,
              label: item.REGIONNAME.val,
            }));
            // 获取区列表
            if( this.areaList.length==0){  //没有区就不要
              this.formValidate.areaId = '';
              this.formValidate.area = '';
            }
            if (this.smartArea) { //智能识别到区获取区ID
              this.getAreaNum(this.smartArea,data.value);
            }
          });
        }
      },
      // 点击后获取市
      selectProvinceBtn(val) {
        let data = this.provinceList.find((item) => item.label == val);
        if(data){
          this.formValidate.provinceId=data.value;
          this.formValidate.province=data.label;
          
          // 市
          let virtual = {
            table: 'T_OMSREGION_CITY',
            isdroplistsearch: true,
            range: 1000,
            startindex: 0,
            fixedcolumns: { PARENTID: [`=${data.value}`] },
          };
          network.post('/p/cs/list/query', virtual).then((res) => {
            this.cityList = res.data.rows.map((item) => ({
              value: item.ID.val,
              label: item.REGIONNAME.val,
            }));
            // 获取市列表
            this.areaList = [];
          });
        }
        
      },
      // 点击后选择区
      selectAreaBtn(val) {
        let data = this.areaList.find((item) => item.label == val);
        if (data) {
          this.formValidate.areaId = data.value;
          this.formValidate.area = data.label;
        }else{
          this.formValidate.areaId = '';
          this.formValidate.area = '';
        }
      },
      // 点击后获取市
      selectCityBtn(val) {
        let data = this.cityList.find((item) => item.label == val);
        if (data) {
          this.formValidate.cityId=data.value;
          this.formValidate.city=data.label;
          // 市
          let virtual = {
            table: 'T_OMSREGION_AREA',
            isdroplistsearch: true,
            range: 1000,
            startindex: 0,
            fixedcolumns: { PARENTID: [`=${data.value}`] },
          };
          network.post('/p/cs/list/query', virtual).then((res) => {
            this.areaList = res.data.rows.map((item) => ({
              value: item.ID.val,
              label: item.REGIONNAME.val,
            }));
            if( this.areaList.length==0){  //没有区就不要
              this.formValidate.areaId = '';
              this.formValidate.area = '';
            }
            // 获得区县
          });
        }
      },
      // 智能识别获取省编号
      getProvinceNum(province) {
        let virtual = {
          table: 'T_OMSREGION_PROVINCE',
          isdroplistsearch: false,
          range: 1000,
          startindex: 0,
          fixedcolumns: { REGIONNAME: province },
        };
        network.post('/p/cs/list/query', virtual).then((res) => {
          if (res.data.rows.length) {
            this.formValidate.provinceId = res.data.rows[0].ID.val;
            this.formValidate.province = res.data.rows[0].REGIONNAME.val;
            this.selectProvince(this.formValidate.province);
          }
        });
      },
      // 智能识别获取市编号
      getCityNum(city) {
        let virtual = {
          table: 'T_OMSREGION_CITY',
          isdroplistsearch: false,
          range: 1000,
          startindex: 0,
          fixedcolumns: { REGIONNAME: city },
        };
        network.post('/p/cs/list/query', virtual).then((res) => {
          if (res.data.rows.length) {
            this.formValidate.cityId = res.data.rows[0].ID.val;
            this.formValidate.city = res.data.rows[0].REGIONNAME.val;
            this.selectCity(this.formValidate.city);
          }
        });
      },
      // 智能识别获取区编号
      getAreaNum(area,PARENTID) {
        let virtual = {
          table: 'T_OMSREGION_AREA',
          isdroplistsearch: false,
          range: 1000,
          startindex: 0,
          fixedcolumns: { REGIONNAME: [`=${area}`], PARENTID: [`=${PARENTID}`]},
        };
        network.post('/p/cs/list/query', virtual).then((res) => {
          if (res.data.rows.length) {
            this.formValidate.areaId = res.data.rows[0].ID.val;
            this.formValidate.area = res.data.rows[0].REGIONNAME.val;
            this.smartProvince = '';
            this.smartCity = '', 
            this.smartArea = '';
          }
        });
      },
      // 智能识别回车事件
      searchsmart(e){
        if(e.keyCode == 13) {
          // 智能识别前清空信息
          // this.formValidate.town = ''; // 街道
          this.smartParse()
        }
      },
      // 智能识别
      smartParse() {
        const [smartResult] = AddressParse.parse(this.formValidate.desc);
        this.formValidate.postCode = smartResult.zip_code?smartResult.zip_code:this.formValidate.postCode;
        this.formValidate.detailAddress = smartResult.details?smartResult.details:this.formValidate.detailAddress;
        this.formValidate.mobile = smartResult.mobile?smartResult.mobile:this.formValidate.mobile;
        this.formValidate.name = smartResult.name?smartResult.name:this.formValidate.name;
        this.formValidate.phone = smartResult.phone?smartResult.phone:this.formValidate.phone;
        this.smartProvince = smartResult.province?smartResult.province:this.smartProvince;
        // this.smartCity = smartResult.city;
        this.smartCity = smartResult.city == '省直辖县'?smartResult.area: smartResult.city;  // 跟系统统一，如果识别出的市区为省直辖县，带入识别出来的区
        this.smartArea = smartResult.area;
        // 有省
        if (smartResult.province) {
          this.smartProvince = smartResult.province;
          this.getProvinceNum(this.smartProvince);
        }
      },
      submit() {
        if (!this.formValidate.name) {
          this.$Message.error('请输入姓名');
          return;
        }
        if (!this.formValidate.province) {
          this.$Message.error('请输入收件人省');
          return;
        }
        if (!this.formValidate.city) {
          this.$Message.error('请输入收件人市');
          return;
        }
        if (!this.formValidate.detailAddress) {
          this.$Message.error('请输入详细地址');
          return;
        }
        
        if (!(this.formValidate.mobile || this.formValidate.phone)) {
          this.$Message.error('请输入手机号或电话');
          return;
        }
        var ss=/[*]+/;
        var r=ss.test(this.formValidate.mobile)||ss.test(this.formValidate.name)||ss.test(this.formValidate.detailAddress);
        if(r){
            this.$Message.error('收货人信息不能存在*号');
            return;
        };
        let reg = RegExp(/(~{2,}|\${2,}|#{2,}|&{2,})/);
        let judge1=reg.test(this.formValidate.detailAddress)||reg.test(this.formValidate.name) ||reg.test(this.formValidate.phone) ||reg.test(this.formValidate.mobile);
        // let judge2=/^(?=.*?[\u4E00-\u9FA5])[\d\u4E00-\u9FA5]{1,}/.test(this.formValidate.detailAddress)
        if(judge1){
          this.$Message.error('收货人信息不能存在##,~~,&&,$$号');
          return;
        }

        // let reg18=/^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dXx]$/;
        // let reg15=/^[1-9]\d{7}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$/;

        // if(this.IS_OVERSEAS && ((!this.formValidate.customs_clearance_type || !this.formValidate.customs_clearance_info) || (!(reg18.test(this.formValidate.customs_clearance_info))&&!(reg15.test(this.formValidate.customs_clearance_info))))){
        //   this.$Message.error('清关信息格式填写错误！');
        //   return;
        // }
         if (this.IS_OVERSEAS && (!this.formValidate.customs_clearance_type || !this.formValidate.customs_clearance_info)) {
          this.$Message.error('清关信息不能为空!');
          return;
        }

        let fixedData = {
          "T_V_OMSONLINEORDER":{
              "RECEIVNAME": this.formValidate.name,
              "RECEIVMOBILE": this.formValidate.mobile,
              "RECEIVPHONE": this.formValidate.phone,
              "RECEIVPROVINCE": this.formValidate.provinceId,
              "RECEIVPROVINCENAME": this.formValidate.province,
              "RECEIVCITY": this.formValidate.cityId,
              "RECEIVCITYNAME": this.formValidate.city,
              "RECEIVAREA": this.formValidate.areaId,
              "RECEIVAREANAME": this.formValidate.area,
              "receivtown": this.formValidate.town,
              "RECEIVADDRESS": this.formValidate.detailAddress,
              "RECEIVZIP": this.formValidate.postCode,
              "RECEIVCOUNTRY": this.formValidate.receiveContry, // 收货人国家
          }
        }
        // 海外订单证件类型和证件号码
        if (this.IS_OVERSEAS) {
          fixedData.T_V_OMSONLINEORDER["customs_clearance_type"] = this.formValidate.customs_clearance_type || "";
          fixedData.T_V_OMSONLINEORDER["customs_clearance_info"] = this.formValidate.customs_clearance_info || "";
        }
        let params = {
          ids: this.idArray,
          fixedData: fixedData
        };
        network.post('/p/cs/BatchAddrModify', params).then(res => {
          if (res.data.code == 0) {
            this.$Modal.fcSuccess({
              title: '提示',
              mask: true,
              content: res.data.message,
            });
            this.closeDialog();
          } else {
            this.$Modal.fcError({
              title: '提示',
              mask: true,
              content: res.data.message,
            });
          }
        });
      },
      cancel() {
        this.closeDialog();
      },
      closeDialog() { // 关闭弹窗
        this.$emit('closeActionDialog', true);
      },
    }
  };
</script>
<style>
  .batchChangeAddress .ark-select-single .ark-select-selection {
    height: 26px;
  }
</style>
<style scoped>
    .batchChangeAddress form {
        margin-right: 30px;
    }
    .text1 /deep/ .ark-input {
        height: 80px;
        resize: none;
        background-color: #f5f5f5;
    }
</style>
