<template>
  <div class="order-manage-wrapper" v-if="showChangeInfo">
    <el-dialog
        title="修改买家收货信息"
        :visible="changeInfoDialog"
        @close="cancelChangeInfo"
        width="600px"
        center
        class="send-set-body">
      <el-form ref="changeInfoForm" :model="changeInfoForm" :rules="rules" label-width="90px" label-suffix=":">
        <el-form-item label="收货人" prop="receiver">
          <el-input type="text" v-model="changeInfoForm.receiver" placeholder="请输入收货人姓名" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="receiverMobile">
          <el-input type="text" v-model="changeInfoForm.receiverMobile" maxlength="11" placeholder="请输入收货人手机号" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="area">
          <el-cascader
              size="small"
              ref="cascaderRegion"
              :options="optionsRegion"
              :props="props"
              v-model="changeInfoForm.area"
              @change="handleChange"
              filterable
              style="width: 100%"
              placeholder="请选择地区"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input type="textarea"
                    v-model="changeInfoForm.address"
                    rows="5"
                    placeholder="请输入收货人详细地址"
                    style="width: 100%;">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitChange">完成</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import { openLoading, closeLoading } from "@/utils/utils";
  import * as operationData from "@/utils/operation";
  import { checkMobile } from '@/utils/patients/checkValid'
  let vm = null;
  export default {
    components: {
    },
    props: {
      showChangeInfo: {
        type: Boolean,
        default: false,
      },
      receiveInfo: {
        type: Object,
        required: true,
        default: () => {}
      },
    },
    data(){
      return{
        changeInfoDialog: true,
        optionsRegion: [],
        administrativeValue: '',
        changeInfoForm: {
          receiver: '',
          receiverMobile: '',
          area: [],
          address: '',
          provinceName: '',
          cityName: '',
          countyName: '',
          townName: '',
          provinceId: null,
          cityId: null,
          countyId: null,
          townId: null,
        },
        provinceList: [],
        cityList: [],
        countyList: [],
        townList: [],
        region: [],
        props: {
          value: "id",
          label: "name",
          children: "children",
          lazy: true,
          lazyLoad(node, resolve) {
            const { level } = node;
            console.log("node", node);
            if (node.level == 1) {
              vm.changeInfoForm.provinceName = node.data.label;
              vm.changeInfoForm.provinceId = node.data.value;
              let req = {
                provinceId: node.data.id
              };
              vm.GET("basic-data/position/cities", req).then(res => {
                let newData = res.data.cityList;
                vm.cityList = res.data.cityList;
                newData.map(item => {
                  vm.$set(item, "id", item.cityId);
                  vm.$set(item, "name", item.cityName);
                  vm.$set(item, "children", []);
                });
                // console.log("newData", newData);
                resolve(newData);
              });
            } else if (node.level == 2) {
              vm.changeInfoForm.cityName = node.data.label;
              vm.changeInfoForm.cityId = node.data.value;
              let req = {
                cityId: node.data.id
              };
              vm.GET("basic-data/position/counties", req).then(res => {
                let newData = res.data.countyList;
                vm.countyList = res.data.countyList;
                newData.map(item => {
                  vm.$set(item, "id", item.countyId);
                  vm.$set(item, "name", item.countyName);
                  vm.$set(item, "children", []);
                });
                // console.log("newData", newData);
                resolve(newData);
              });
            } else if (node.level == 3) {
              vm.changeInfoForm.countyName = node.data.label;
              vm.changeInfoForm.countyId = node.data.value;
              let req = {
                countyId: node.data.id
              };
              vm.GET("basic-data/position/towns", req).then(res => {
                let newData = res.data.townList;
                vm.townList = res.data.townList;
                newData.map(item => {
                  vm.$set(item, "id", item.townId);
                  vm.$set(item, "name", item.townName);
                  vm.$set(item, "leaf", true);
                });
                // console.log("newData", newData);
                resolve(newData);
              });
            }
          }
        },
        /*props: {
          lazy: true,
          lazyLoad(node, resolve) {
            //第一个参数node为当前点击的节点，第二个resolve为数据加载完成的回调(必须调用)
            const { level } = node;
            console.log("当前点击的节点node", node);
            if (node.level == 1) {
              vm.changeInfoForm.provinceName = node.data.label;
              vm.changeInfoForm.provinceId = node.data.value;
              let req = {
                provinceId: node.data.value
              };
              vm.GET("basic-data/position/cities", req).then(res => {
                vm.cityList = res.data.cityList;
                let newData = vm.setMoreOption(res.data.cityList, "cities");
                resolve(newData);
              });
            } else if (node.level == 2) {
              vm.changeInfoForm.cityName = node.data.label;
              vm.changeInfoForm.cityId = node.data.value;
              let req = {
                cityId: node.data.value
              };
              vm.GET("basic-data/position/counties", req).then(res => {
                vm.countyList = res.data.countyList;
                let newData = vm.setMoreOption(res.data.countyList, "counties");
                resolve(newData);
              });
            } else if (node.level == 3) {
              vm.changeInfoForm.countyName = node.data.label;
              vm.changeInfoForm.countyId = node.data.value;
              let req = {
                countyId: node.data.value
              };
              vm.GET("basic-data/position/towns", req).then(res => {
                vm.townList = res.data.townList;
                let newData = vm.setMoreOption(res.data.townList, "towns");
                resolve(newData);
              });
            }
          }
        },*/
        rules: {
          receiver: [
            { required: true, message: '请输入收货人姓名', trigger: "blur"},
          ],
          receiverMobile: [
            { required: true, message: '请输入收货人手机号', trigger: "blur"},
            {validator: checkMobile, trigger: 'blur'}
          ],
          area: [
            { required: true, message: '请选择所在地区', trigger: "blur"},
          ],
          address: [
            { required: true, message: '请输入收货人详细地址', trigger: "blur"},
          ],
        },
      }
    },
    created() {
      vm = this;

    },
    watch: {
      async showChangeInfo(val) {
        if (val) {
          await this.initData();
        }
      },
    },
    methods: {
      async initData() {
        await this.getRegionOption()
        console.log('父级传入的值',this.receiveInfo);
        const { receiver, receiverMobile,  provinceId, provinceName, cityId, cityName, countyId, countyName, townId, townName, address } = this.receiveInfo;
        this.changeInfoForm.receiver = receiver;
        this.changeInfoForm.receiverMobile = receiverMobile;
        this.changeInfoForm.address = address;
        this.changeInfoForm.provinceId = provinceId;
        this.changeInfoForm.provinceName = provinceName;
        this.changeInfoForm.cityId = cityId;
        this.changeInfoForm.cityName = cityName;
        this.changeInfoForm.countyId = countyId;
        this.changeInfoForm.countyName = countyName;
        this.changeInfoForm.townId = townId;
        this.changeInfoForm.townName = townName;

        //对地区数据做回显处理
        if(provinceId) {

          // if(provinceId) {
            await this.getCity(provinceId);
          // }
          if(cityId) {
            await this.getCounty(provinceId, cityId);
          }
          if(countyId) {
            await this.getTown(provinceId, cityId, countyId);
          }

          this.changeInfoForm.area = [Number(provinceId), Number(cityId), Number(countyId), Number(townId)];
          this.$forceUpdate();
        }else {
          this.changeInfoForm.area = [];
        }
        console.log('传入值处理后',this.changeInfoForm)
       /*let arrayLike = {
          0: provinceId,
          1: cityId,
          2: countyId,
          3: townId,
          'length': 4
        }
        let arr = Array.from(arrayLike)
        console.log('初始化后的值',arr);*/
      },
      handleChange(value) {
        let areaId = "000";
        for (let i = 0; i < value.length; i++) {
          areaId += "_" + value[i];
        }
        this.administrativeValue = areaId;
        console.log('修改后的值',value, this.administrativeValue);
      //  000_110_110100000000_110101000000_110101001000

        setTimeout(function() {
          let region = vm.$refs["cascaderRegion"].inputValue;
          vm.region = region.split(" / ");
          // console.log("vm.region",vm.region)
        },20)
      },
      //获取地区
      async getRegionOption() {
        let req = {};
        // openLoading(vm);
        // vm.GET("basic-data/position/provinces", req).then(res => {
        //   closeLoading(vm);
        //   if (res.code == "000000") {
        //     this.provinceList = res.data.provinceList;
        //     vm.optionsRegion = operationData.setRegionOption3(
        //       res.data.provinceList
        //     );
        //     console.log('region',vm.optionsRegion)
        //   }
        // });

        vm.GET("basic-data/position/provinces", req).then((data) => {
          if(data.code == '000000') {
            this.provinceList = data.data.provinceList;
            this.provinceList.map(item => {
              this.$set(item, "id", item.provinceId);
              this.$set(item, "name", item.provinceName);
              this.$set(item, "children", []);
            });
            this.optionsRegion = this.provinceList;
            // this.$forceUpdate();
          }
        })
      },
      async getCity(provinceId) {
        await vm.GET("basic-data/position/cities", {provinceId: provinceId}).then((data) => {
          if(data.code == '000000') {
            this.cityList = data.data.cityList;
            this.cityList.map(item => {
              this.$set(item, "id", item.cityId);
              this.$set(item, "name", item.cityName);
              this.$set(item, "children", []);
            });
            this.optionsRegion.map((item, index) => {
              if(item.id == provinceId) {
                item.children = this.cityList;
              }
            })
          }
        })
      },
      async getCounty(provinceId, cityId) {
        await vm.GET("basic-data/position/counties", {cityId: cityId}).then((data) => {
          if(data.code == '000000') {
            this.countyList = data.data.countyList;
            this.countyList.map(item => {
              this.$set(item, "id", item.countyId);
              this.$set(item, "name", item.countyName);
              this.$set(item, "children", []);
            });
            this.optionsRegion.map((item, index) => {
              if(item.id == provinceId) {
                item.children.map((city, idx) => {
                  if(city.id == cityId) {
                    city.children = this.countyList;
                  }
                })
              }
            })
          }
        })
      },
      async getTown(provinceId, cityId, countyId) {
        await vm.GET("basic-data/position/towns", {countyId: countyId}).then((data) => {
          if(data.code == '000000') {
            this.townList = data.data.townList;
            this.townList.map(item => {
              this.$set(item, "id", item.townId);
              this.$set(item, "name", item.townName);
              this.$set(item, "leaf", true);
            });
            this.optionsRegion.map((item, index) => {
              if(item.id == provinceId) {
                item.children.map((city, index2) => {
                  if(city.id == cityId) {
                    city.children.map((county, index3) => {
                      if(county.id == countyId) {
                        county.children = this.townList;
                      }
                    })
                  }
                })
              }
            })
          }
        })
      },
      setMoreOption(data, type) {
        let option = [];
        for (let i = 0; i < data.length; i++) {
          let obj = data[i];
          if (type == "cities") {
            obj.label = data[i].cityName;
            obj.value = data[i].cityId;
          } else if (type == "counties") {
            obj.label = data[i].countyName;
            obj.value = data[i].countyId;
            // obj.leaf = true;
          } else if (type == "towns") {
            obj.label = data[i].townName;
            obj.value = data[i].townId;
            obj.leaf = true;
          }
          option.push(obj);
        }
        return option;
      },
      cancelChangeInfo() {
        this.$emit('closeChangeInfo',{type: 1})
      },
      setAreaData() {
        if(this.changeInfoForm.area.length > 0) {
          this.changeInfoForm.provinceId = this.changeInfoForm.area[0];
          this.changeInfoForm.cityId = this.changeInfoForm.area[1];
          this.changeInfoForm.countyId = this.changeInfoForm.area[2];
          this.changeInfoForm.townId = this.changeInfoForm.area[3];
          if (vm.region.length) {
            this.changeInfoForm.provinceName = vm.region[0];
            this.changeInfoForm.cityName = vm.region[1];
            this.changeInfoForm.countyName = vm.region[2];
            this.changeInfoForm.townName = vm.region[3];
          }
        }
      },
      submitChange() {
        this.$refs.changeInfoForm.validate((valid) => {
          if (valid) {
            // this.submit();
            this.setAreaData();
            // this.changeInfoForm.townId = null;
            // this.changeInfoForm.townName = '';
            // if (this.changeInfoForm.area.length == 4) {
            //   this.changeInfoForm.townId = this.changeInfoForm.area[3];
            //   this.townList.map((item) => {
            //     if (this.changeInfoForm.townId == item.townId) {
            //       this.changeInfoForm.townName = item.townName;
            //     }
            //   })
            // }
            console.log('确定值',this.changeInfoForm)
            this.$emit('closeChangeInfo',{type: 2, data: this.changeInfoForm})
          } else {
            return false;
          }
        })
      },
    },
  }
</script>
<style lang="scss">
  .send-set-body{
    .address-content{
      width: 100%;
      background-color: #F0F2F5;
      border: 1px solid #E4E7ED;
      border-radius: 4px;
      padding: 10px 15px;
      .address-title{
        display: flex;
        justify-content: space-between;
        align-items: center;
        .title{
          font-size: 13px;
          color: #999999;
        }
      }
      .address-info{
        p{
          line-height: 26px;
        }
      }
    }
    .form-title{
      margin-top: 15px;
      margin-bottom: 15px;
    }
    .el-dialog__body{
      padding-bottom: 0;
    }
  }
</style>
