// 列表-条件查询

<template>
  <div class="search-form-wapper">
    <el-form :inline="true" :model="form" ref="search-form" size="small">
      <el-form-item
        v-for="(item, i) in search"
        :key="i"
        v-bind:class="{ search_new_line: item.newLine }"
      >
        <el-input
          class="input_el"
          v-model="form[item.name]"
          v-if="item.type === 'text'"
          :placeholder="
            item.placeholder ? item.placeholder : '请输入' + 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 && item.change"
          @clear="item.clear && item.clear"
          v-if="item.type === 'select'"
          :placeholder="'请选择' + item.label"
        >
          <!-- <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]"
          :filterable="item.filterable"
          :multiple="item.multiple"
          :clearable="true"
          @change="salaChange"
          @clear="item.clear && item.clear"
          v-if="item.type === 'selectSalaId'"
          :placeholder="'请选择' + item.label"
        >
          <el-option
            :label="label.deptName"
            :value="label.id"
            v-for="(label, value) in salaArr"
            :key="value"
          ></el-option>
        </el-select>
        <el-select
          v-model="form[item.name]"
          :filterable="item.filterable"
          :multiple="item.multiple"
          :clearable="true"
          @clear="item.clear && item.clear"
          v-if="item.type === 'selectDeptId'"
          :placeholder="'请选择' + item.label"
        >
          <!-- <el-option
            label=""
            value=""
            v-if="!item.multiple && !item.notShowAll"
          ></el-option> -->
          <el-option
            :label="label.deptName"
            :value="label.id"
            v-for="(label, value) in deptArr"
            :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="item.label ? item.label : '选择日期'"
        >
        </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="item.label ? item.label : '选择日期'"
        >
        </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="item.label ? item.label : '选择月份'"
        >
        </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="item.label ? item.label : '选择月份'"
        >
        </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="item.label"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="onSubmit"
          title="查询"
          >查询</el-button
        >
        <!-- <el-button
          icon="el-icon-tickets"
          @click="resetTable"
          v-if="visible"
          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" title="清空"
          >清空</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Qs from "qs";
import { type } from "@/assets/utils";
import { isArray } from "util";
import {
  getFirstDay,
  getLastDay,
  timestampToTime,
} from "@/assets/utils/dateFormat.js";
export default {
  props: {
    search: {
      type: Array,
      default: () => [],
    },
    table: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    $route(route) {
      this.initForm(route.query);
    },
  },
  async created() {
    this.cleanForm();
    // this.$route.query ? (this.$route.query = {}) : console.log(456);
    this.$route.name == "attendance/stat/list"
      ? (this.visible = true)
      : (this.visible = false);
    if (
      this.$route.name == "attendance/stat/list" ||
      this.$route.name == "check/window/perform/list" ||
      this.$route.name == "check/window/workman/perform/list" ||
      this.$route.name == "check/window/workman/perform/detail/list" ||
      this.$route.name == "check/attend/record/list" ||
      this.$route.name == "check/review/record/list" ||
      this.$route.name == "check/complain/record/list" ||
      this.$route.name == "check/gowork/record/list" ||
      this.$route.name == "check/effect/record/list" ||
      this.$route.name == "check/other/record/list" ||
      this.$route.name == "window/perform/list" ||
      this.$route.name == "window/workman/perform/list" ||
      this.$route.name == "perform/attend/record/list" ||
      this.$route.name == "perform/review/record/list" ||
      this.$route.name == "perform/complain/record/list" ||
      this.$route.name == "perform/gowork/record/list" ||
      this.$route.name == "perform/effect/record/list" ||
      this.$route.name == "perform/other/record/list" ||
      this.$route.name == "perform/attend/appeal/list" ||
      this.$route.name == "window/owner/list" ||
      this.$route.name == "staff/perform/summary/list" ||
      this.$route.name == "attendance/record/list" ||
      this.$route.name == "attendance/record/error/list" ||
      this.$route.name == "attendance/leave/record/list" ||
      this.$route.name == "attendance/vacation/balance/list"
    ) {
      this.getArr();
    }

    this.initForm(this.$route.query);
  },
  methods: {
    salaChange() {
      this.form.deptId = "";
      this.$get("/dept/getDeptBySalaId", { salaId: this.form.salaId })
        .then((res) => {
          if (res.code == 1) {
            this.deptArr = res.data.data;
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    getArr() {
      this.$get("/dept/getSalaList")
        .then((res) => {
          if (res.code == 1) {
            this.salaArr = res.data.data;
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
      this.$get("/dept/getDeptBySalaId")
        .then((res) => {
          if (res.code == 1) {
            this.deptArr = res.data.data;
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    resetTable() {
      let { path, query } = this.$route;
      if (this.form.attendanceDateStart && this.form.attendanceDateEnd) {
        let startValue = Date.parse(this.form.attendanceDateStart);
        let endValue = Date.parse(this.form.attendanceDateEnd);
        if (startValue > endValue) {
          this.$message.error("查询-结束的日期需大于开始日期");
          this.form.attendanceDateEnd = "";
          return false;
        }
      }

      if (this.form.startTime && this.form.endTime) {
        let startValue = Date.parse(this.form.startTime);
        let endValue = Date.parse(this.form.endTime);
        if (startValue > endValue) {
          this.$message.error("查询-结束的日期需大于开始日期");
          this.form.endTime = "";
          return false;
        }
      }
      if (this.$route.name == "attendance/stat/list") {
        if (this.form.summaryTimeStart && this.form.summaryTimeEnd) {
          let startValue = Date.parse(this.form.summaryTimeStart);
          let endValue = Date.parse(this.form.summaryTimeEnd);
          if (startValue > endValue) {
            this.$message.error("查询-结束的日期需大于开始日期");
            this.form.summaryTimeEnd = "";
            return false;
          }
        } else {
          this.form.summaryTimeStart = getFirstDay();
          this.form.summaryTimeEnd = getLastDay();
        }
      } else {
        delete this.form.summaryTimeStart;
        delete this.form.summaryTimeEnd;
      }
      if (this.$route.name == "attendance/record/error/list") {
        if (this.form.errorDateTimeStart && this.form.errorDateTimeEnd) {
          let startValue = Date.parse(this.form.errorDateTimeStart);
          let endValue = Date.parse(this.form.errorDateTimeEnd);
          if (startValue > endValue) {
            this.$message.error("查询-结束的日期需大于开始日期");
            this.form.errorDateTimeEnd = "";
            return false;
          }
        } else {
          this.form.errorDateTimeStart = getFirstDay();
          this.form.errorDateTimeEnd = getLastDay();
        }
      } else {
        delete this.form.errorDateTimeStart;
        delete this.form.errorDateTimeEnd;
      }
      if (this.$route.name == "attendance/record/hik/list") {
        if (this.form.attendanceDateStart && this.form.attendanceDateEnd) {
          let startValue = Date.parse(this.form.attendanceDateStart);
          let endValue = Date.parse(this.form.attendanceDateEnd);
          if (startValue > endValue) {
            this.$message.error("查询-结束的日期需大于开始日期");
            this.form.attendanceDateEnd = "";
            return false;
          }
        } else {
          this.form.attendanceDateStart = getFirstDay();
          this.form.attendanceDateEnd = getFirstDay();
        }
      }

      let params = JSON.parse(JSON.stringify(this.form)); //不更改原始数据
      let data = this.decode(params);
      data.size = -1;
      this.$post("/attendance/stat/summary", data).then((res) => {
        if (res.code == 1) {
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    remoteMethod(query, searchType) {
      if (query == "") {
        console.log("查询参数为空！");
        return;
      }
      this.loading = true;
      var param = {
        name: 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];
            }
          }
        }
      });

      this.form = Object.assign({}, this.form, newFormData);
      // this.form = Object.assign({}, this.form, data);
      // console.log("after form",this.form)
    },
    cleanForm() {
      this.clean();
    },
    // 清空表单值
    clean() {
      let newData = {};
      this.search.forEach((item) => {
        if (item.name === "groupList") {
          newData[item.name] = [];
        } else {
          newData[item.name] = item.multiple ? [] : "";
        }
      });

      delete this.$route.query.yearmonth;
      delete this.$route.query.createTimeMonth;
      delete this.$route.query.orderColList;

      this.form = Object.assign({}, this.form, newData);
      if (
        this.$route.name == "check/window/workman/perform/detail/list" ||
        this.$route.name == "window/perform/summary/list"
      ) {
        this.form.yearmonth = timestampToTime(new Date(), 2);
        this.form.year = timestampToTime(new Date(), 2).slice(0, 4);
        this.form.month = timestampToTime(new Date(), 2).slice(5);
      }
      this.form.idList ? (this.form.idList = []) : "";
      if (this.$route.name == "staff/leave/list") {
        this.form.idList = "";
      }
      this.onSubmit();
    },
    onSubmit() {
      let { path, query } = this.$route;
      if (this.form.yearmonth) {
        let arr = this.form.yearmonth.split("-");
        this.form.year = arr[0];
        this.form.month = arr[1];
      } else {
        this.form.year = undefined;
        this.form.month = undefined;
      }

      if (this.form.createTimeMonth) {
        // this.form.createTimeStart = this.form.createTimeMonth + "-01";
        // this.form.createTimeEnd = this.form.createTimeMonth + "-31";
        this.form.errorTimeStart = this.form.createTimeMonth + "-01";
        this.form.errorTimeEnd = this.form.createTimeMonth + "-31";
        this.form.reviewTimeStart = this.form.createTimeMonth + "-01";
        this.form.reviewTimeEnd = this.form.createTimeMonth + "-31";
        this.form.complainTimeStart = this.form.createTimeMonth + "-01";
        this.form.complainTimeEnd = this.form.createTimeMonth + "-31";
        this.form.goworkTimeStart = this.form.createTimeMonth + "-01";
        this.form.goworkTimeEnd = this.form.createTimeMonth + "-31";
        this.form.happenTimeStart = this.form.createTimeMonth + "-01";
        this.form.happenTimeEnd = this.form.createTimeMonth + "-31";
      } else if (this.form.createTimeStart1 || this.form.createTimeEnd1) {
        this.form.createTimeStart = this.form.createTimeStart1;
        this.form.createTimeEnd = this.form.createTimeEnd1;
      } else {
        this.form.createTimeStart = undefined;
        this.form.createTimeEnd = undefined;
      }
      if (this.form.attendanceDateStart && this.form.attendanceDateEnd) {
        let startValue = Date.parse(this.form.attendanceDateStart);
        let endValue = Date.parse(this.form.attendanceDateEnd);
        if (startValue > endValue) {
          this.$message.error("查询-结束的日期需大于开始日期");
          this.form.attendanceDateEnd = "";
          return false;
        }
      }

      if (this.form.startTime && this.form.endTime) {
        let startValue = Date.parse(this.form.startTime);
        let endValue = Date.parse(this.form.endTime);
        if (startValue > endValue) {
          this.$message.error("查询-结束的日期需大于开始日期");
          this.form.endTime = "";
          return false;
        }
      }

      if (this.$route.name == "attendance/stat/list") {
        if (this.form.summaryTimeStart && this.form.summaryTimeEnd) {
          let startValue = Date.parse(this.form.summaryTimeStart);
          let endValue = Date.parse(this.form.summaryTimeEnd);
          if (startValue > endValue) {
            this.$message.error("查询-结束的日期需大于开始日期");
            this.form.summaryTimeEnd = "";
            return false;
          }
        } else {
          this.form.summaryTimeStart = getFirstDay();
          this.form.summaryTimeEnd = getLastDay();
        }
      } else {
        delete this.form.summaryTimeStart;
        delete this.form.summaryTimeEnd;
      }
      if (this.$route.name == "attendance/record/error/list") {
        if (this.form.errorDateTimeStart && this.form.errorDateTimeEnd) {
          let startValue = Date.parse(this.form.errorDateTimeStart);
          let endValue = Date.parse(this.form.errorDateTimeEnd);
          if (startValue > endValue) {
            this.$message.error("查询-结束的日期需大于开始日期");
            this.form.errorDateTimeEnd = "";
            return false;
          }
        } else {
          this.form.errorDateTimeStart = getFirstDay();
          this.form.errorDateTimeEnd = getLastDay();
        }
      } else {
        delete this.form.errorDateTimeStart;
        delete this.form.errorDateTimeEnd;
      }
      if (this.$route.name == "attendance/record/hik/list") {
        if (this.form.attendanceDateStart && this.form.attendanceDateEnd) {
          let startValue = Date.parse(this.form.attendanceDateStart);
          let endValue = Date.parse(this.form.attendanceDateEnd);
          if (startValue > endValue) {
            this.$message.error("查询-结束的日期需大于开始日期");
            this.form.attendanceDateEnd = "";
            return false;
          }
        } else {
          this.form.attendanceDateStart = timestampToTime(new Date(), 3);
          this.form.attendanceDateEnd = timestampToTime(new Date(), 3);
        }
      }
      if (this.$route.name == "perform/effect/record/list") {
        this.form.subMethod ? "" : (this.form.subMethod = "1");
        console.log(this.form.subMethod);
      }
      let params = JSON.parse(JSON.stringify(this.form)); //不更改原始数据
      let data = this.decode(params);

      // Object.assign({}, query, data)

      if (!query.yearmonth) {
        query.year = undefined;
        query.month = undefined;
      }
      if (!query.createTimeMonth) {
        if (query.createTimeStart1 || query.createTimeEnd1) {
          query.createTimeEnd = query.createTimeEnd1;
          query.createTimeStart = query.createTimeStart1;
        } else {
          query.createTimeEnd = undefined;
          query.createTimeStart = undefined;
          query.errorTimeStart = undefined;
          query.errorTimeEnd = undefined;
        }
      }

      console.log({
        ...query,
        ...data,
      });
      this.$router.push({
        path: path,
        query: {
          ...query,
          ...data,
        },
      });
    },
    // 解析url字符串，去除query字段
    encode(data, formTemp) {
      let newData = {};
      Object.keys(Qs.parse(data)).forEach((item) => {
        console.log(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;
    },

    // 解析url字符串，加入query字段
    decode(data) {
      let newData = { page: 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();
            if (val.charAt(0) != "%") {
              val = "%" + val;
            }
            if (val.charAt(val.length - 1) != "%") {
              val = val + "%";
            }
          }
        });
        newData[item] = this.decodeVal(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;
    },

    listChange() {},
  },
  computed: {},
  data() {
    return {
      downloadUrl: false,
      form: {
        // groupList: [],
      },
      remoteOptions: {},
      visible: false,
      salaArr: [],
      deptArr: [],
    };
  },
};
</script>

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

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