<template>
  <div class="picker-wrap">
    <div
      class="picker-wrap-txt"
      :class="{ placeholder: !String(pickerValShow) }"
      @click="show = true"
    >
      <span>{{ pickerValShow || placeholder }}</span>
      <svg-icon icon-class="triangle-right" slot="button" />
    </div>
    <cr-popup v-model="show" position="bottom" get-container="body">
      <cr-area ref="area" :value="value" :list="areaList" @cancel="onCancel" @confirm="onConfirm" />
    </cr-popup>
  </div>
</template>

<script>
import popupPickerMixin from "../mixins/popupPicker.mixin.js";
import areaList from "@qg/cherry-ui/src/area/demo/china";
export default {
  name: "PopupAreaPicker",
  mixins: [popupPickerMixin],
  data() {
    return {
      refName: "area",
      areaList,
      pickerDefaultVal: ""
    };
  },
  watch: {
    value(val) {
      if (val) {
        this.setDefaultVal(false);
      }
    }
  },
  methods: {
    handleResult(res) {
      let valShow = [];
      let val = [];
      res.forEach(item => {
        valShow.push(item.name || item.text);
        val.push(item.code);
      });
      this.pickerValShow = valShow.join(",");
      this.pickerVal = val[2];
    },
    setDefaultVal(setCol = true) {
      setTimeout(() => {
        const $area = this.$refs.area;
        const $picker = $area.$refs.picker;
        const val = this.value;
        let columns = "";
        $area.selectedCodes = [`${val.substring(0, 2)}0000`, `${val.substring(0, 4)}00`, val];
        $area.renderProvince();
        // 防止refresh把数据刷没
        columns = JSON.parse(JSON.stringify($area.columns));
        if (setCol) {
          $picker.setColumnIndex(0, columns[0].selectedIndex);
          $picker.setColumnIndex(1, columns[1].selectedIndex);
          $picker.setColumnIndex(2, columns[2].selectedIndex);
        } else {
          const province = columns[0].values[columns[0].selectedIndex];
          const city = columns[1].values[columns[1].selectedIndex];
          const country = columns[2].values[columns[2].selectedIndex];
          this.handleResult([province, city, country]);
        }
      });
    }
  }
};
</script>
<style lang="less">
.picker-wrap {
  width: 100%;
  &-txt {
    height: 24px;
    color: #333;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .svg-icon {
    height: 16px;
    width: 16px;
  }
  .placeholder {
    color: #ccc;
  }
}
</style>
