<template>
  <div class="app-container">
    <el-form :inline="true" :model="queryParams">
      <el-form-item :label="$t('area.areaName')">
        <el-input
          v-model="queryParams.areaName"
          :placeholder="$t('share.PleaseEnter') + $t('area.areaName')"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('area.regionCode')">
        <el-input
          v-model="queryParams.areaCode"
          :placeholder="$t('share.PleaseEnter') + $t('area.regionCode')"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('area.areaType')">
        <el-select
          v-model="queryParams.areaType"
          :placeholder="$t('share.PleaseChoose') + $t('area.areaType')"
        >
          <el-option
            :label="item.dictLabel"
            :value="item.dictValue"
            v-for="item in areaTypeData"
            :key="item.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t("share.search") }}</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("share.reset")
        }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          plain
          size="mini"
          @click="add"
          >{{ $t("share.new") }}</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-sort"
          plain
          size="mini"
          @click="toggleExpandAll(isExpandAll)"
          >{{ $t("area.UnfoldAndFold") }}</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleExport">{{
          $t("share.export")
        }}</el-button>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="areaId"
      :default-expand-all="isExpandAll"
      :key="treeKey"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="areaName" :label="$t('area.areaName')">
      </el-table-column>
      <el-table-column
        prop="areaCode"
        :label="$t('area.regionCode')"
        width="180"
        align="center"
      >
      </el-table-column>

      <el-table-column prop="orderNum" :label="$t('area.sort')" align="center">
      </el-table-column>
      <el-table-column :label="$t('area.areaType')" align="center">
        <template slot-scope="scope">
          <el-tag type="success">{{ areaTypeFn(scope.row.areaType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        :label="$t('share.CreationTime')"
        align="center"
      >
      </el-table-column>
      <el-table-column :label="$t('share.operate')" width="180" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="handleEdit(scope.row.areaId)"
            >{{ $t("share.edit") }}</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleAdd(scope.row.areaId)"
            >{{ $t("share.new") }}</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleDelete(scope.row.areaId)"
            v-if="scope.row.parentId !== 0"
            >{{ $t("share.delete") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <el-row :gutter="10">
        <el-form
          :model="dialogForm"
          label-width="130px"
          :rules="rules"
          ref="ruleForm"
        >
          <el-col :span="12" v-if="dialogForm.parentId !== 0">
            <el-form-item :label="$t('area.SuperiorRegion')" prop="parentId">
              <treeSelect
                :menuOptions="menuOptions"
                @selectValue="selectValue"
                :editData="editData"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('area.areaType')" style="width: 100%">
              <el-select
                v-model="dialogForm.areaType"
                :placeholder="$t('share.PleaseChoose') + $t('area.areaType')"
              >
                <el-option
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  v-for="item in areaTypeData"
                  :key="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('area.areaName')" prop="areaName">
              <el-input
                v-model="dialogForm.areaName"
                :placeholder="$t('share.PleaseEnter') + $t('area.areaName')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('area.regionCode')">
              <el-input
                v-model="dialogForm.areaCode"
                :placeholder="$t('share.PleaseEnter') + $t('area.regionCode')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('area.sort')" prop="orderNum">
              <el-input-number
                v-model="dialogForm.orderNum"
                controls-position="right"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{
          $t("share.cancel")
        }}</el-button>
        <el-button type="primary" @click="submitForm">{{
          $t("share.confirm")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  areaType,
  postRemove,
  postAdd,
  getItem,
  edit,
} from "@/api/area/area";
// import Treeselect from "@riophae/vue-treeselect";
// import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import treeSelect from "./components/treeSelect.vue";
export default {
  components: { treeSelect },
  data() {
    return {
      treeKey: 0,
      queryParams: {},
      tableData: [],
      dialogVisible: false,
      title: this.$t("area.AddArea"),
      dialogForm: {},
      rules: {
        // parentId: [
        //   {
        //     required: true,
        //     message:
        //       this.$t("share.PleaseChoose") + this.$t("area.SuperiorRegion"),
        //     trigger: "change",
        //   },
        // ],
        areaName: [
          {
            required: true,
            message: this.$t("share.PleaseEnter") + this.$t("area.areaName"),
            trigger: "blur",
          },
        ],
        orderNum: [
          {
            required: true,
            message: this.$t("share.PleaseChoose") + this.$t("area.sort"),
            trigger: "change",
          },
        ],
      },
      areaTypeData: [],
      queryParamsType: 0,
      // 多级下拉
      menuOptions: [],
      type: 0,
      editData: {},
      isExpandAll: true,
    };
  },
  mounted() {
    this.init();
    areaType().then((res) => {
      console.log(res, 1111111);
      if (res.code == 200) {
        this.areaTypeData = res.data;
      }
    });
  },
  methods: {
    // 初始化
    init() {
      getList(this.queryParams).then((res) => {
        if (res.code == 200) {
          this.menuOptions = this.tableListFn(res.data);
          if (this.queryParamsType == 0) {
            this.tableData = this.tableListFn(res.data);
          } else {
            this.tableData = res.data;
          }

          this.$message({
            type: "success",
            message: "查询成功",
          });
        }
      });
    },
    //表格扁平转树结构
    tableListFn(list = []) {
      var map = {};
      var tree = [];

      // 只克隆一次
      const clonedList = list.map((item) => ({
        ...item,
        children: item.children ? [...item.children] : [],
      }));

      // 构建 map
      for (const item of clonedList) {
        map[item.areaId] = item;
      }

      // 构建父子关系
      for (const item of clonedList) {
        if (item.parentId !== 0 && map[item.parentId]) {
          map[item.parentId].children.push(item);
        } else {
          tree.push(item);
        }
      }

      return tree;
    },
    areaTypeFn(type) {
      var name = "";
      this.areaTypeData.forEach((item) => {
        if (item.dictValue == type) {
          name = item.dictLabel;
        }
      });
      return name;
    },
    // 查询
    handleQuery() {
      console.log(this.queryParams);
      if (JSON.stringify(this.queryParams) === "{}") {
        this.queryParamsType = 0;
      } else {
        this.queryParamsType = 1;
      }
      this.init();
    },
    // 重置
    resetQuery() {
      this.queryParams = {};
      this.queryParamsType = 0;
      this.init();
    },
    add() {
      this.dialogForm = {};
      this.type = 0;
      this.dialogVisible = true;
      this.title = this.$t("area.AddArea");
    },
    handleEdit(id) {
      this.type = 1;
      this.title = this.$t("area.EditArea");
      getItem(id).then((res) => {
        if (res.code == 200) {
          this.dialogForm = res.data;
          this.editData = res.data;
          this.dialogVisible = true;
        }
      });
    },
    handleAdd(areaId) {
      this.type = 0;
      this.dialogForm = {};
      this.dialogForm.parentId = areaId;
      let data = {
        parentId: areaId,
      };
      this.title = this.$t("area.AddArea");
      this.editData = data;
      this.dialogVisible = true;
    },
    selectValue(val) {
      this.dialogForm.parentId = val;
    },
    submitForm() {
      if (!this.dialogForm.parentId)
        return this.$message.error("请选择上级区域");
      if (this.type == 0) {
        postAdd(this.dialogForm).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "添加成功!",
            });
            this.dialogVisible = false;
            this.init();
          }
        });
      } else {
        edit(this.dialogForm).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "编辑成功!",
            });
            this.dialogVisible = false;
            this.init();
          }
        });
      }
    },
    // 删除
    handleDelete(id) {
      this.$confirm(`确定要删除Id为${id}的数据吗？`, "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          postRemove(id).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.init();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    toggleExpandAll(isExpandAll) {
      this.treeKey = +new Date();
      this.isExpandAll = !isExpandAll;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/basedata/area/export",
        {
          ...this.queryParams,
        },
        `area_${new Date().getTime()}.xlsx`
      );
    },
    handleClose() {},
  },
};
</script>

<style lang="scss" scoped>
::v-deep.el-input-number {
  width: 100%;
}
</style>
