<template>
  <div>
    <el-cascader
      v-model="cityData"
      v-show="edit"
      :options="provinceOptions"
      @expand-change="handleItemChange"
      @change="handleChange"
      @focus="handleFocus"
      :separator="separator"
      :placehold="placeholder"
      :disabled="disabled"
      :clearable="clearable"
      :props="cityProps"
    ></el-cascader>
    <div v-show="!edit" class="el-form-item__content aos-form-input-text">
      <div :title="realValue">
        {{realValue}}
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'AosCity',
  props: {
    // 编辑状态
    edit: {
      type: Boolean,
      default: true
    },
    // 省
    province: {
      type: String,
      default: '',
      required: true
    },
    // 市
    city: {
      type: String,
      default: '',
      required: true
    },
    // 县
    county: {
      type: String,
      default: '',
      required: true
    },
    //
    templateValue: {
      type: Object,
      required: true
    },
    // 禁用状态
    disabled: {
      type: Boolean,
      default: false
    },
    // 提示
    placeholder: {
      type: String,
      default: '请选择省/市/县'
    },
    // 选项分隔符
    separator: {
      type: String,
      default: '/'
    },
    clearable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      provinceOptions: [],
      cityProps: {
        label: 'value',
        value: 'code',
        children: 'citys'
      },
      cityData: [],
      realValue: ''
    };
  },
  created() {
    if (this.edit) {
      let provide = this.getProvince();
      window.Promise.all([provide]).then(() => {
        this.init();
      });
    } else {
      this.init();
    }
  },
  methods: {
    handleItemChange(val) {
      if (val.length === 1) {
        this.getCity('', val);
      } else if (val.length === 2) {
        this.getCounty('', val);
      } else if (val.length === 3) {
        if (!val[1]) {
          this.getCity('', val);
        } else if (!val[2]) {
          this.getCounty('', val);
        }
      }
    },
    getProvince(query) {
      if (!query) {
        query = '';
      }
      let params = {
        query: query
      };
      return this.$optimizeHttp({
        url: '/ap/area-info/ref',
        method: 'post',
        params: params
      }).then((res) => {
        this.provinceOptions = res.data;
        if (this.provinceOptions && this.provinceOptions.length > 0) {
          this.provinceOptions.forEach((item) => {
            this.$set(item, 'citys', []);
          });
        }
      }).catch(() => {
        this.$message({
          typr: 'error',
          message: '请求省份信息出错'
        });
      });
    },
    getCity(query, val) {
      let params = {
        query: query,
        parentId: val[0]
      };
      this.$optimizeHttp({
        url: '/ap/area-info/ref',
        method: 'post',
        params: params
      }).then((res) => {
        let cityOptions = res.data;
        cityOptions.forEach((item) => {
          this.$set(item, 'citys', []);
        });
        for (let i = 0;i < this.provinceOptions.length;i++) {
          if (val[0] === this.provinceOptions[i].code) {
            this.provinceOptions[i].citys = cityOptions;
            break;
          }
        }
      }).catch(() => {
        this.$message({
          typr: 'error',
          message: '请求市级信息出错'
        });
      });
    },
    getCounty(query, val) {
      let params = {
        query: query,
        parentId: val[1]
      };
      this.$optimizeHttp({
        url: '/ap/area-info/ref',
        method: 'post',
        params: params
      }).then((res) => {
        let countyOptions = res.data;
        let parentOption = [];
        for (let i = 0;i < this.provinceOptions.length;i++) {
          if (val[0] === this.provinceOptions[i].code) {
            parentOption = this.provinceOptions[i].citys;
            break;
          }
        }
        for (let i = 0;i < parentOption.length;i++) {
          if (val[1] === parentOption[i].code) {
            parentOption[i].citys = countyOptions;
            break;
          }
        }

      }).catch(() => {
        this.$message({
          typr: 'error',
          message: '请求市级信息出错'
        });
      });
    },
    handleFocus(event) {
      this.$emit('focus', event);
    },
    handleChange(val) {
      this.setRealValue(val);
    },
    setRealValue(val) {
      let cityOption = [];
      let countyOption = [];
      let changeValue = {};
      for (let i = 0;i < this.provinceOptions.length;i++) {
        if (val[0] === this.provinceOptions[i].code) {
          cityOption = this.provinceOptions[i].citys;
          changeValue.provinceName = this.provinceOptions[i].value;
          changeValue.provinceCode = this.provinceOptions[i].code;
          break;
        }
      }
      for (let i = 0;i < cityOption.length;i++) {
        if (val[1] === cityOption[i].code) {
          countyOption = cityOption[i].citys;
          changeValue.cityName = cityOption[i].value;
          changeValue.cityCode = cityOption[i].code;
          break;
        }
      }
      for (let i = 0;i < countyOption.length;i++) {
        if (val[2] === countyOption[i].code) {
          changeValue.countyName = countyOption[i].value;
          changeValue.countyCode = countyOption[i].code;
          break;
        }
      }
      this.realValue = changeValue.provinceName + '/' + changeValue.cityName + '/' + changeValue.countyName;
      this.templateValue[this.province] = val[0];
      this.templateValue[this.city] = val[1];
      this.templateValue[this.county] = val[2];
      this.$emit('change', changeValue);
    },
    init() {
      let beanMap = void 0;
      let cityValue = void 0;
      let beanMapName = this.province + '_' + this.city + '_' + this.county + '_city';
      if (this.templateValue && this.templateValue.beanMap) {
        beanMap = JSON.parse(this.templateValue.beanMap);
      }
      if (beanMap && beanMap[beanMapName]) {
        cityValue = beanMap[beanMapName];
        this.cityData = [
          cityValue.provinceCode, cityValue.cityCode, cityValue.countyCode
        ];
        if (!this.edit) {
          this.provinceOptions.push({
            value: cityValue.provinceName,
            code: cityValue.provinceCode,
            citys: [{
              value: cityValue.cityName,
              code: cityValue.cityCode,
              citys: [{
                value: cityValue.countyName,
                code: cityValue.countyCode
              }]
            }]
          });
        } else {
          for (let i = 0;i < this.provinceOptions.length;i++) {
            if (cityValue.provinceCode === this.provinceOptions[i].code) {
              this.$set(this.provinceOptions[i], 'citys', []);
              this.provinceOptions[i].citys.push({
                value: cityValue.cityName,
                code: cityValue.cityCode,
                citys: [{
                  value: cityValue.countyName,
                  code: cityValue.countyCode
                }]
              });
              break;
            }
          }
        }
        this.realValue = cityValue.provinceName + '/' + cityValue.cityName + '/' + cityValue.countyName;
      }
    }
  },
  computed: {
    templateBeanMap: function() {
      if (this.templateValue.beanMap) {
        return this.templateValue.beanMap;
      } else {
        return '';
      }
    },
    templateProvince: function() {
      return this.templateValue[this.province];
    },
    templateCity: function() {
      return this.templateValue[this.city];
    },
    templateCounty: function() {
      return this.templateValue[this.county];
    }
  },
  watch: {
    templateBeanMap: {
      handler() {
        this.init();
      },
      deep: true
    },
    templateProvince: {
      handler() {
        this.init();
      },
      deep: true
    },
    templateCity: {
      handler() {
        this.init();
      },
      deep: true
    },
    templateCounty: {
      handler() {
        this.init();
      },
      deep: true
    }
  }
};
</script>

