<template>
  <el-dialog
    :title="$t1('地区列表')"
    :append-to-body="true"
    :modal-append-to-body="true"
    :close-on-click-modal="falseValue"
    :visible.sync="showDialog"
    :modal="falseValue"
    custom-class="dialog-style list-dialog dialog-checkbox pd_0"
    width="1200px"
    @close="dialogClose"
    v-el-drag-dialog
    v-el-dialog-center
  >
    <template #title>
      <span class="el-dialog__title"
        >{{ $t1("地区列表")
        }}<span style="margin-left: 10px; margin-right: 10px">—</span> {{ $t1("国家") }}：
        <el-input
          class="search-input"
          max="200"
          v-model="countryName"
          @clear="cleaerCountry"
          placeholder="默认中国"
          v-el-readonly
          clearable
        >
          <i
            slot="suffix"
            class="el-input__icon el-icon-search"
            @click="showCountryDialog = true"
          ></i> </el-input
      ></span>
    </template>
    <div class="cont" style="height: 450px">
      <el-tabs v-model="activeName" class="tab-box">
        <el-tab-pane :label="$t1('下拉选择')" name="first">
          <el-popover placement="bottom" width="630" trigger="click" ref="select1">
            <div class="adr-select-box">
              <div
                class="item"
                v-for="(item, index) in provinces"
                :key="index"
                :class="[value1 == item.id ? 'on' : '']"
                @click="checkItem(item, 1)"
              >
                <span>{{ item.name }}</span>
              </div>
            </div>
            <label class="adr-select-txt" :class="{ noNone: !!value1 }" slot="reference">
              <!--              <i :class="row.menuImg" class="iconfont"></i>-->
              <span v-if="!!value1">{{ getItemLabel(provinces, value1) }}</span>
              <span v-if="!value1" style="color: #e8e8e8">{{ $t1("请选择") }}</span>
              <i class="el-icon-arrow-down"></i>
              <i
                class="el-icon-circle-close icon-box_del"
                @click.stop="clearCheckItem(1)"
              ></i>
            </label>
          </el-popover>
          <el-popover
            :disabled="selectTopLevel || !value1 || cities.length == 0"
            placement="bottom"
            width="486"
            trigger="click"
            ref="select2"
          >
            <div class="adr-select-box">
              <div
                class="item"
                v-for="(item, index) in cities"
                :key="index"
                :class="[value2 == item.id ? 'on' : '']"
                @click="checkItem(item, 2)"
              >
                <span>{{ item.name }}</span>
              </div>
            </div>
            <label class="adr-select-txt" :class="{ noNone: !!value2 }" slot="reference">
              <!--              <i :class="row.menuImg" class="iconfont"></i>-->
              <span v-if="!!value2">{{ getItemLabel(cities, value2) }}</span>
              <span v-if="!value2" style="color: #e8e8e8">{{ $t1("请选择") }}</span>
              <i class="el-icon-arrow-down"></i>
              <i
                class="el-icon-circle-close icon-box_del"
                @click.stop="clearCheckItem(2)"
              ></i>
            </label>
          </el-popover>
          <el-popover
            :disabled="selectTopLevel || !value2 || districts.length == 0"
            placement="bottom"
            width="486"
            trigger="click"
            ref="select3"
          >
            <div class="adr-select-box">
              <div
                class="item"
                v-for="(item, index) in districts"
                :key="index"
                :class="[value3 == item.id ? 'on' : '']"
                @click="checkItem(item, 3)"
              >
                <span>{{ item.name }}</span>
              </div>
            </div>
            <label class="adr-select-txt" :class="{ noNone: !!value3 }" slot="reference">
              <!--              <i :class="row.menuImg" class="iconfont"></i>-->
              <span v-if="!!value3">{{ getItemLabel(districts, value3) }}</span>
              <span v-if="!value3" style="color: #e8e8e8">{{ $t1("请选择") }}</span>
              <i class="el-icon-arrow-down"></i>
              <i
                class="el-icon-circle-close icon-box_del"
                @click.stop="clearCheckItem(3)"
              ></i>
            </label>
          </el-popover>
          <el-popover
            :disabled="selectTopLevel || !value3 || counties.length == 0"
            placement="bottom"
            width="486"
            trigger="click"
            ref="select4"
          >
            <div class="adr-select-box">
              <div
                class="item"
                v-for="(item, index) in counties"
                :key="index"
                :class="[value4 == item.id ? 'on' : '']"
                @click="checkItem(item, 4)"
              >
                <span>{{ item.name }}</span>
              </div>
            </div>
            <label class="adr-select-txt" :class="{ noNone: !!value4 }" slot="reference">
              <!--              <i :class="row.menuImg" class="iconfont"></i>-->
              <span v-if="!!value4">{{ getItemLabel(counties, value4) }}</span>
              <span v-if="!value4" style="color: #e8e8e8">{{ $t1("请选择") }}</span>
              <i class="el-icon-arrow-down"></i>
              <i
                class="el-icon-circle-close icon-box_del"
                @click.stop="clearCheckItem(4)"
              ></i>
            </label>
          </el-popover>
        </el-tab-pane>
        <el-tab-pane :label="$t1('列表选择')" name="second">
          <div style="height: 400px">
            <vxe-grid
              class="is-pointer"
              ref="table-m1"
              v-bind="vxeOption"
              @resizable-change="$vxeTableUtil.onColumnWitchChange"
              @custom="$vxeTableUtil.customHandle"
              @checkbox-change="addDataTable"
              @checkbox-all="checkAll"
              @cell-dblclick="checkWithSubmit"
            >
              <template #form v-if="!(param && param.onlySearchTopLevel)">
                <div class="clearfix screen-btns">
                  <div class="fr">
                    <vxe-button
                      icon="el-icon-brush"
                      class="button-sty"
                      @click="resetEvent"
                      type="text"
                      status="primary"
                      plain
                      >{{ $t1("重置") }}
                    </vxe-button>
                    <vxe-button
                      status="warning"
                      icon="el-icon-search"
                      class="button-sty"
                      @click="searchEvent"
                    >
                      {{ $t1("搜索") }}
                    </vxe-button>
                  </div>
                </div>
                <vxe-form
                  class="screen-box"
                  title-width="92px"
                  title-align="right"
                  :data="formData"
                  @submit="searchEvent"
                  @reset="resetEvent"
                >
                  <vxe-form-item :title="$t1('地区名称') + ':'" field="name">
                    <template v-slot>
                      <el-input v-model="formData.name" size="small" clearable />
                    </template>
                  </vxe-form-item>
                  <vxe-form-item :title="$t1('地区全称') + ':'" field="fullName">
                    <template v-slot>
                      <el-input v-model="formData.fullName" size="small" clearable />
                    </template>
                  </vxe-form-item>
                  <vxe-button
                    type="submit"
                    @click="searchEvent"
                    v-show="false"
                  ></vxe-button>
                </vxe-form>
              </template>
            </vxe-grid>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <label id="labBtn" class="transverse">
      <div class="icon">
        <i class="el-icon-more"></i>
        <i class="el-icon-more"></i>
      </div>
    </label>
    <div class="multipleChoice">
      <el-tooltip
        :enterable="false"
        effect="dark"
        :content="$t1('全部删除')"
        placement="top"
        ><a class="allDel icon-quanbushanchu" @click="clearChecked()"></a
      ></el-tooltip>
      <div class="list">
        <div class="item" v-for="(checkRow, index) in checkRows" :key="index">
          <p>{{ checkRow.fullName }}</p>
          <a class="el-icon-close" @click="clearTable1Select(index)"></a>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <span class="fl tips" v-if="!selectMulti">{{
        $t1("注：双击确认选择（单选）")
      }}</span>
      <el-button type="primary" plain class="button-sty" @click="dialogClose">
        <i class="el-icon-close el-icon"></i>
        {{ $t1("取 消") }}
      </el-button>
      <el-button type="primary" @click="dialogPrimary" class="button-sty">
        <i class="el-icon-check el-icon"></i>
        {{ $t1("确 定") }}
      </el-button>
    </span>
    <countryDialog
      v-if="showCountryDialog"
      :visiable.sync="showCountryDialog"
      :multi="false"
      @confirm="countryDialogConfirm"
    ></countryDialog>
  </el-dialog>
</template>

<script>
import { selectDialogMixins } from "@base/mixins/selectDialog/index.js";
import countryDialog from "@base/views/user/country/dialog.vue";

export default {
  name: "areaDialog",
  props: ["visiable", "multi", "rows", "param", "selectTopLevel"],
  mixins: [selectDialogMixins],
  components: { countryDialog },
  created() {
    this.initSetting();
  },
  mounted() {
    this.getAreaData(0, 1);
    this.initTableM1();
  },
  data() {
    var that = this;
    return {
      showDialog: true,
      falseValue: false,
      selectMulti: true,
      formData: {},
      vxeOption: {},
      checkItemIds: [],
      activeName: "second",
      provinces: [],
      cities: [],
      districts: [],
      counties: [],
      value1: null,
      value2: null,
      value3: null,
      value4: null,
      tableInited: false,
      showCountryDialog: false,
      countryName: null,
      locale: null,
    };
  },
  watch: {
    activeName(val) {
      if (val == "second") {
        if (!this.tableInited) {
          this.$nextTick(() => {
            this.initTableM1();
          });
          this.tableInited = true;
        } else {
          this.searchEvent();
        }
      } else {
        this.clearCheckItem(1);
      }
      this.checkRows = [];
    },
  },
  methods: {
    clearCheckItem(level) {
      this.checkRows = [];
      if (level == 1) {
        this.value1 = null;
        this.value2 = null;
        this.value3 = null;
        this.value4 = null;
        this.cities = [];
        this.districts = [];
        this.counties = [];
      } else if (level == 2) {
        this.value2 = null;
        this.value3 = null;
        this.value4 = null;
        this.districts = [];
        this.counties = [];
        let value = this.value1;
        let item = this.provinces.find((item) => item.id == value);
        if (item) {
          this.checkRows.push(item);
        }
      } else if (level == 3) {
        this.value3 = null;
        this.value4 = null;
        this.counties = [];
        let value = this.value2;
        let item = this.cities.find((item) => item.id == value);
        if (item) {
          this.checkRows.push(item);
        }
      } else if (level == 4) {
        this.value4 = null;
        let value = this.value3;
        let item = this.districts.find((item) => item.id == value);
        if (item) {
          this.checkRows.push(item);
        }
      }

      this.$refs["select1"].showPopper = false;
      this.$refs["select2"].showPopper = false;
      this.$refs["select3"].showPopper = false;
      this.$refs["select4"].showPopper = false;
    },
    checkItem(row, level) {
      if (level == 1) {
        if (this.value1 !== row.id) {
          this.value1 = row.id;
          this.value2 = null;
          this.value3 = null;
          this.value4 = null;
          this.cities = [];
          this.districts = [];
          this.counties = [];
          this.getAreaData(row.id, level + 1);
          this.checkRows = [row];
        }
      } else if (level == 2) {
        if (this.value2 !== row.id) {
          this.value2 = row.id;
          this.value3 = null;
          this.value4 = null;
          this.districts = [];
          this.counties = [];
          this.getAreaData(row.id, level + 1);
          this.checkRows = [row];
        }
      } else if (level == 3) {
        if (this.value3 !== row.id) {
          this.value3 = row.id;
          this.value4 = null;
          this.counties = [];
          this.getAreaData(row.id, level + 1);
          this.checkRows = [row];
        }
      } else if (level == 4) {
        if (this.value4 !== row.id) {
          this.value4 = row.id;
          this.checkRows = [row];
        }
      }
      this.$refs["select" + level].showPopper = false;
    },
    getItemLabel(items, value) {
      if (value) {
        let currentItem = items.find((item) => item.id == value);
        if (currentItem) {
          return currentItem.name;
        } else {
          return null;
        }
      } else {
        return null;
      }
    },
    changeSelect(value, level) {},
    getAreaData(id, level) {
      let locale = this.locale || null;
      this.$http({
        url: USER_PREFIX + "/area/getChildren",
        method: "post",
        data: {
          id: id,
          locale: locale,
          enabled: true,
        },
        success: (res) => {
          // const {level} = node;
          let isLeaf = level >= 4;
          let rows = res.objx || [];
          rows.forEach((row) => {
            rows.leaf = isLeaf;
          });
          if (level == 1) {
            this.provinces = rows;
          } else if (level == 2) {
            this.cities = rows;
          } else if (level == 3) {
            this.districts = rows;
          } else if (level == 4) {
            this.counties = rows;
          }
        },
      });
    },
    initTableM1() {
      let that = this;
      let tableOption = {
        vue: that,
        tableRef: "table-m1",
        tableName: "basicAreaDialogList",
        path: USER_PREFIX + "/area/list",
        treeNodeUrl: USER_PREFIX + "/area/getChildren",
        treeNodeParam(row) {
          return {
            id: row.id,
            enabled: true,
          };
        },
        param: () => {
          let locale = this.locale || null;
          return {
            enabled: true,
            ...this.formData,
            ...this.param,
            locale: locale,
          };
        },
        columns: [
          { type: "checkbox", fixed: "left", width: 48, resizable: false },
          {
            title: this.$t1("地区名称"),
            field: "name",
            width: 250,
            fixed: "left",
            // treeNode: true,
            treeNode: !(this.param && this.param.onlySearchTopLevel),
          },
          {
            field: "fullName",
            title: this.$t1("地区全称"),
            width: 250,
          },
          {
            width: 47,
            fixed: "right",
            title: "",
            sortable: false,
          },
        ],
        config: {
          checkboxConfig: {
            checkStrictly: true,
            showHeader: this.selectMulti,
            trigger: "row",
            checkMethod: ({ row }) => {
              if (this.selectTopLevel) {
                if (row.parent) {
                  return false;
                } else {
                  return true;
                }
              }

              return true;
            },
          },
        },
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then((opts) => {
        that.vxeOption = opts;
      });
    },
    cleaerCountry() {
      this.countryName = null;
      this.locale = null;

      this.clearCheckItem(1);
      this.getAreaData(0, 1);
      this.searchEvent();
    },
    countryDialogConfirm(rows) {
      if (rows.length > 0) {
        let row = rows[0];
        this.locale = row.countryCode;
        this.countryName = row.simpleName;

        this.clearCheckItem(1);
        this.getAreaData(0, 1);
        this.resetEvent();
      }
    },
  },
};
</script>
<style scoped lang="scss">
.el-select-dropdown__item .iconfont {
  vertical-align: middle;
  margin-right: 3px;
}

.icons-box_select {
  .el-icon-circle-close {
    display: none;
  }
}

.icons-box_select.noNone:hover {
  .el-icon-arrow-down {
    display: none;
  }

  .el-icon-circle-close {
    display: inline-block;
  }
}

::v-deep .dialog-style .multipleChoice .list .item > p {
  max-width: inherit;
}
</style>
