// 列表-条件查询

<template>
  <div class="search-form-wapper">
    <el-form :inline="true" :model="form" ref="search-form" size="small">
      <!-- 省市区选择器 -->
      <template v-if="areaSelect.enable">
        <el-form-item label="区域">
          <el-cascader
            v-model="area"
            clearable="true"
            filterable
            change-on-select
            @change="treeSelected"
            :options="treeData"
          ></el-cascader>
        </el-form-item>
      </template>

      <el-form-item
        :label="item.label"
        v-for="(item, i) in search"
        :key="i"
        v-bind:class="{ search_new_line: item.newLine }"
      >
        <el-input
          v-model="form[item.name]"
          v-if="item.type === 'text'"
          :placeholder="
            item.placeholder
              ? item.placeholder
              : item.fuzzy !== true
              ? '请输入' + item.label
              : '支持模糊查询'
          "
        ></el-input>

        <el-checkbox-group
          v-model="form[item.name]"
          v-if="item.type === 'checkbox'"
        >
          <el-checkbox
            v-for="(label, value) in table.dict[item.name]"
            :label="value"
            :key="value"
            >{{ label }}</el-checkbox
          >
        </el-checkbox-group>

        <el-select
          v-model="form[item.name]"
          :filterable="item.filterable"
          :multiple="item.multiple"
          clearable="true"
          @change="item.change"
          @clear="item.clear"
          v-if="item.type === 'select'"
        >
          <el-option
            label="全部"
            value=""
            v-if="!item.multiple && !item.notShowAll"
          ></el-option>
          <el-option
            :label="label"
            :value="value"
            v-for="(label, value) in table.dict[item.name]"
            :key="value"
          ></el-option>
        </el-select>

        <el-select
          v-model="form[item.name]"
          clearable
          :multiple="item.multiple"
          filterable
          remote
          v-if="item.type === 'remoteSelect'"
          placeholder="请输入关键词"
          searchType="item.searchType"
          :remote-method="
            (query) => {
              remoteMethod(query, item.searchType);
            }
          "
        >
          <el-option
            :label="label"
            :value="value"
            v-for="(label, value) in remoteOptions[item.searchType]"
            :key="value"
          ></el-option>
        </el-select>

        <el-cascader
          placeholder="选择区域"
          v-if="item.type === 'cascader'"
          v-model="selectedTreeID"
          :filterable="item.filterable"
          clearable="true"
          change-on-select
          @change="treeSelecteds"
          :options="treeDatas"
        ></el-cascader>

        <el-select
          v-model="form[item.name]"
          :multiple="item.multiple"
          :remote-method="userRemoteMethod"
          :loading="loading"
          @focus="userRemoteMethod"
          :reserve-keyword="item.reserve - keyword"
          :clearable="item.clearable"
          :placeholder="item.placeholder ? item.placeholder : '请输入用户'"
          filterable
          remote
          v-if="item.type === 'userLoginNameRemoteSelect'"
        >
          <el-option
            v-for="i in userData"
            :key="i.loginName"
            :label="i.realName"
            :value="i.loginName"
          ></el-option>
        </el-select>

        <el-date-picker
          v-model="form[item.name]"
          v-if="item.type === 'date' && !item.valueFormat"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
        >
        </el-date-picker>

        <el-date-picker
          v-model="form[item.name]"
          v-if="item.type === 'date' && item.valueFormat"
          type="date"
          :value-format="item.valueFormat"
          placeholder="选择日期"
        >
        </el-date-picker>

        <el-date-picker
          v-model="form[item.name]"
          v-if="item.type === 'month' && !item.valueFormat"
          type="month"
          value-format="yyyy-MM"
          placeholder="选择月份"
        >
        </el-date-picker>

        <el-date-picker
          v-model="form[item.name]"
          v-if="item.type === 'month' && item.valueFormat"
          type="month"
          :value-format="item.valueFormat"
          placeholder="选择月份"
        >
        </el-date-picker>

        <el-date-picker
          v-model="form[item.name]"
          v-if="item.type === 'datetime'"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间"
        >
        </el-date-picker>


      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="onSubmit"
          circle
          title="查询"
        ></el-button>
        <el-button
          icon="el-icon-download"
          @click="downloadFile"
          :loading="isDownload"
          v-if="downloadUrl"
          >下载</el-button
        >
        <el-button
          icon="el-icon-refresh-left"
          @click="cleanForm"
          circle
          title="清空"
        ></el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Qs from "qs";
import {
  type,
  download,
  downloadWithCustName,
  getUserListByQuery,
} from "@/assets/utils";
import { treeCache } from "@/assets/utils/tree";
import { isArray } from "util";

export default {
  props: {
    search: {
      type: Array,
      default: () => [],
    },
    table: {
      type: Object,
      default: () => {},
    },
    downloadUrl: {
      type: String,
      default: "",
    },
    areaSelect: {
      type: Object,
      default: () => {
        return {
          enable: false,
          level: 1, // 1，仅区域
        };
      },
    },
  },
  watch: {
    $route(route) {
      this.initForm(route.query);
    },
  },
  async created() {
    this.treeDatas = await treeCache.getTree();
    if (this.areaSelect.enable) {
      this.treeData = await treeCache.getTree();
    }
    let tempAreaId = this.$route.query["query.areaId"];
    if (tempAreaId) {
      this.selectedTreeID = treeCache.getPid(Number(tempAreaId));
    }
    this.initForm(this.$route.query);
  },
  methods: {
    afterRender() {
      this.selectedTreeID = treeCache.getPid(this.form.areaId);
    },
    beforeSubmit(form) {
      form.areaId = this.selectedTreeID.slice().pop();
      return form;
    },
    treeSelecteds(val) {
      this.form.areaId = val.slice().pop();
    },
    remoteMethod(query, searchType) {
      if (query == "") {
        return;
      }
      this.loading = true;
      var param = {
        "query.name": query,
        "query.searchType": searchType,
      };
      try {
        this.$post("/common/autoComplete/list", param).then(({ data }) => {
          this.loading = false;
          var tempOptions = {};
          data.result.forEach(({ id, name }) => {
            tempOptions[id] = name;
          });
          this.remoteOptions[searchType] = Object.assign({}, tempOptions);
          sessionStorage.setItem(
            searchType + "OptionsDict",
            JSON.stringify(this.remoteOptions[searchType])
          );
        });
      } catch (error) {}
    },
    async initForm(data) {
      let newFormData = {};
      this.form = this.encode(data, this.form);
      this.search.forEach((item) => {
        if (item.type === "checkbox") {
          if (this.form[item.name] == undefined) {
            newFormData[item.name] = [];
          } else if (Array.prototype.isPrototypeOf(this.form[item.name])) {
            newFormData[item.name] = this.form[item.name];
          } else {
            newFormData[item.name] = [this.form[item.name]];
          }
        } else if (item.multiple === true) {
          if (this.form[item.name] == undefined) {
            this.form[item.name] = [];
            newFormData[item.name] = [];
          } else {
            if (!isArray(this.form[item.name])) {
              var temp = this.form[item.name];
              this.form[item.name] = [temp];
              newFormData[item.name] = [temp];
            }
          }
        }
        if (item.type === "remoteSelect") {
          if (
            this.form[item.name] == undefined ||
            (item.multiple === true && this.form[item.name].length == 0)
          ) {
            this.remoteOptions[item.searchType] = {};
          } else {
            this.remoteOptions[item.searchType] = JSON.parse(
              sessionStorage.getItem(item.searchType + "OptionsDict")
            );
          }
        }
      });
      this.form = Object.assign({}, this.form, newFormData);
      //this.form = Object.assign({}, this.form, this.encode(data));
      // 区域选择器
      if (this.areaSelect.enable) {
        this.form.areaId = this.form.areaId ? this.form.areaId : 510100;
        this.area = treeCache.getPid(this.form.areaId).map(Number);
        this.treeSelected(this.area, "man");
      }
    },
    cleanForm() {
      this.clean();
      this.onSubmit();
    },
    // 清空表单值
    clean() {
      let newData = {};
      this.search.forEach((item) => {
        if (item.name === "groupList") {
          newData[item.name] = [];
        } else {
          newData[item.name] = item.multiple ? [] : undefined;
        }
      });
      if (this.areaSelect.enable) {
        newData.areaId = "";
        this.area = [510000, 510100];
      }
      this.form = Object.assign({}, this.form, newData);
      this.selectedTreeID = [];
    },
    onSubmit() {
      let { path, query } = this.$route;
      let data = this.decode(this.form);
      this.$router.push({
        path: path,
        query: Object.assign({}, query, data),
      });
    },
    // 解析url字符串，去除query字段
    encode(data, formTemp) {
      let newData = {};
      Object.keys(Qs.parse(data)).forEach((item) => {
        if (/^query\./.test(item)) {
          let val = data[item];
          let key = item.replace(/^query\./, "");

          this.search.forEach((obj) => {
            if (
              obj.name === key &&
              obj.fuzzy === true &&
              val &&
              val.length > 0
            ) {
              //支持模糊查询,首尾去掉百分号
              val = val.substring(1, val.length - 1);
            }
          });

          let isAreaTemp = ["areaId"];
          let isAreaParam = isAreaTemp.includes(key);
          newData[key] =
            type(val) === "Array"
              ? val.map(isAreaParam ? Number : String)
              : val;
        }
      });
      return newData;
    },
    decodeVal(val) {
      let valType = type(val);
      if (["Number", "Boolean"].indexOf(valType) > -1) {
        return val;
      }
      if (valType == "Undefined" || valType == "Null") {
        return undefined;
      }
      if (valType == "String") {
        let str = val.trim();
        return str.length ? str : undefined;
      }
      return val;
    },
    // 解析url字符串，加入query字段
    decode(data) {
      let newData = { "pageInfo.currPage": 1 };
      Object.keys(data).forEach((item) => {
        let val = data[item];
        this.search.forEach((obj) => {
          if (
            obj.name === item &&
            obj.fuzzy === true &&
            val &&
            val.length > 0
          ) {
            //支持模糊查询,收尾增加百分号
            val = val.trim();
            val = "%" + val + "%";
          }
        });
        newData["query." + item] = this.decodeVal(val);
      });
      return newData;
    },
    // 下载文件
    async downloadFile() {
      let data = this.decode(this.form);
      let searchString = Object.assign({}, this.$route.query, data);
      this.isDownload = true;
      try {
        //        await download(this.downloadUrl, searchString )
        await downloadWithCustName(this.downloadUrl, searchString);
      } catch (error) {
        this.$message.error(error);
      }
      this.isDownload = false;
    },
    // 区域选择
    async treeSelected(val, type) {
      let areas = [];
      const [province, city, area] = val;
      if (!type) {
        this.form.areaId = val.slice().pop();
      }
      // 查找省市关联的区域
      switch (val.length) {
        case 1:
          areas = await treeCache.getAreasByProvinceId([province]);
          break;
        case 2:
          areas = await treeCache.getAreasByCityId([city]);
          break;
        case 3:
          areas = [val[2]];
          break;
        default:
          break;
      }
    },
    //用户远程搜索
    async userRemoteMethod(name) {
      if (name !== "") {
        this.loading = true;
        const userQuery = {
          "pageInfo.prePageResult": 50,
          "query.realName": name,
        };
        this.userData = await getUserListByQuery(userQuery);
        this.loading = false;
      } else {
        this.userData = [];
      }
    },
    listChange() {},
  },
  computed: {},
  data() {
    return {
      form: {
        groupList: [],
      },
      remoteOptions: {},
      treeData: [],
      userData: [],
      area: [],
      isDownload: false,
      treeDatas: [],
      selectedTreeID: [],
    };
  },
};
</script>

<style lang="less">
.search_new_line {
  width: 100%;
}
.search-form-wapper {
  .el-input {
    width: 170px;
  }
  .el-select .el-input {
    width: 140px;
  }
}

@media screen and (max-width: 800px) {
  .search-form-wapper {
    .el-form-item {
      width: 100%;
      .el-form-item__label {
        min-width: 70px;
      }
      .el-input {
        width: 200px;
      }
      .el-select .el-input {
        width: 200px;
      }
    }
  }
}
</style>

