<template>
  <div class="app-container">
    <!-- 搜索工作栏  -->
    <el-form
      v-if="queryData.length"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-position="left"
    >
      <SearchBar :show-span="12" :collapse-span="6" :show-more="false">
        <template #header>
          <template>
            <el-col :span="24">
              <el-button type="text" style="font-weight: bold">{{
                title
              }}</el-button></el-col
            >
            <template v-for="(data, idx) in queryList">
              <el-col :key="idx" :span="9">
                <el-select
                  v-model="queryList[idx].key"
                  style="width: 35%"
                  size="mini"
                  filterable
                  placeholder="请选择"
                  @change="queryKeyChange($event, idx, 'query')"
                >
                  <el-option
                    v-for="(item, i) in searchData"
                    :key="i"
                    :label="item.columnComment"
                    :value="item.columnName"
                  />
                </el-select>
                <DictSelect
                  v-if="data.dataType != 'ym_date_query_type'"
                  v-model="queryList[idx].operate"
                  style="width: 28%"
                  size="mini"
                  placeholder="请选择"
                  :dict-type="data.dataType ? data.dataType.toUpperCase() : ''"
                />
                <el-form-item
                  style="display: inline-block"
                  :style="
                    data.dataType == 'ym_date_query_type'
                      ? 'width: 63%;'
                      : 'width: 35%;'
                  "
                >
                  <!-- 文本域 -->
                  <el-input
                    v-if="data.htmlType == 'textarea'"
                    v-model="queryList[idx].value"
                    type="textarea"
                    :placeholder="'请输入'"
                    clearable
                    size="mini"
                    @keyup.enter.native="handleQuery"
                  />
                  <!-- 日期选择 -->
                  <el-date-picker
                    v-else-if="
                      data.htmlType == 'datetime' ||
                      data.htmlType == 'datetimerange' ||
                      data.htmlType == 'daterange'
                    "
                    v-model="queryList[idx].value"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetimerange"
                    :default-time="['00:00:00', '23:59:59']"
                    placeholder="选择日期"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                  />
                  <!-- 字典下拉 -->
                  <DictSelect
                    v-else-if="data.htmlType == 'select' && data.dictType"
                    v-model="queryList[idx].value"
                    placeholder="请选择"
                    :dict-type="data.dictType.toUpperCase()"
                  />
                  <!-- 字典单选 -->
                  <el-radio-group
                    v-else-if="data.htmlType == 'radio' && data.dictType"
                    v-model="queryList[idx].value"
                  >
                    <el-radio
                      v-for="dict in getDictDatas(
                        DICT_TYPE[data.dictType.toUpperCase()]
                      )"
                      :key="dict.value"
                      :label="parseInt(dict.value)"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                  <!-- 输入框 -->
                  <el-input
                    v-else
                    v-model="queryList[idx].value"
                    :placeholder="'请输入'"
                    clearable
                    size="mini"
                  />
                </el-form-item>
              </el-col>
            </template>
            <el-col :span="6">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
              <el-popover
                v-if="true"
                v-model="visible"
                placement="bottom"
                width="500"
              >
                <div>
                  <template v-for="(data, idx) in querySetList">
                    <el-col :key="idx" :span="24">
                      <el-select
                        v-model="querySetList[idx].key"
                        style="width: 30%"
                        size="mini"
                        placeholder="请选择"
                        filterable
                        @change="queryKeyChange($event, idx, 'querySet')"
                      >
                        <el-option
                          v-for="(item, i) in searchData"
                          :key="i"
                          :label="item.columnComment"
                          :value="item.columnName"
                        />
                      </el-select>
                      <DictSelect
                        v-if="data.dataType != 'ym_date_query_type'"
                        v-model="querySetList[idx].operate"
                        style="width: 25%"
                        size="mini"
                        placeholder="请选择"
                        :dict-type="
                          data.dataType ? data.dataType.toUpperCase() : ''
                        "
                      />
                      <el-form-item
                        style="display: inline-block"
                        :style="
                          data.dataType == 'ym_date_query_type'
                            ? 'width: 55%;'
                            : 'width: 30%;'
                        "
                      >
                        <!-- 文本域 -->
                        <el-input
                          v-if="data.htmlType == 'textarea'"
                          v-model="querySetList[idx].value"
                          type="textarea"
                          :placeholder="'请输入'"
                          clearable
                          size="mini"
                        />
                        <!-- 日期选择 -->
                        <el-date-picker
                          v-else-if="
                            data.htmlType == 'datetime' ||
                            data.htmlType == 'datetimerange' ||
                            data.htmlType == 'daterange'
                          "
                          v-model="querySetList[idx].value"
                          style="width: 100%"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          type="datetimerange"
                          :default-time="['00:00:00', '23:59:59']"
                          placeholder="选择日期"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                        />
                        <!-- 字典下拉 -->
                        <DictSelect
                          v-else-if="data.htmlType == 'select' && data.dictType"
                          v-model="querySetList[idx].value"
                          placeholder="请选择"
                          :dict-type="data.dictType.toUpperCase()"
                        />
                        <!-- 字典单选 -->
                        <el-radio-group
                          v-else-if="data.htmlType == 'radio' && data.dictType"
                          v-model="querySetList[idx].value"
                        >
                          <el-radio
                            v-for="dict in getDictDatas(
                              DICT_TYPE[data.dictType.toUpperCase()]
                            )"
                            :key="dict.value"
                            :label="parseInt(dict.value)"
                            >{{ dict.label }}</el-radio
                          >
                        </el-radio-group>
                        <!-- 输入框 -->
                        <el-input
                          v-else
                          v-model="querySetList[idx].value"
                          :placeholder="'请输入'"
                          clearable
                          size="mini"
                        />
                      </el-form-item>
                      <i
                        v-if="idx != 0"
                        class="el-icon-remove-outline"
                        @click="delQueryItem(idx)"
                      />
                    </el-col>
                  </template>

                  <el-col :span="24">
                    <el-select
                      v-model="querySettingKey"
                      style="width: 30%"
                      filterable
                      size="mini"
                      placeholder="请选择"
                      @change="querySettingKeyChange"
                    >
                      <el-option
                        v-for="(item, i) in searchData"
                        :key="i"
                        :label="item.columnComment"
                        :value="item.columnName"
                      />
                    </el-select>
                  </el-col>
                </div>

                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="visible = false"
                    >取消</el-button
                  >
                  <el-button type="primary" size="mini" @click="queryDataSetOk"
                    >确定</el-button
                  >
                </div>
                <el-button slot="reference" size="mini"
                  ><i class="el-icon-setting"
                /></el-button> </el-popover
            ></el-col>
          </template>
        </template>
        <template #buttons />
      </SearchBar>
    </el-form>

    <!-- 操作工具栏  -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="Export"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="ExportAll"
          >导出全部</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-dropdown
          v-show="dropdownList && dropdownList.length > 0"
          @command="batchCommand"
        >
          <el-button type="primary" size="mini">
            扩展业务功能<i class="el-icon-arrow-down" />
          </el-button>
          <el-dropdown-menu>
            <el-dropdown-item
              v-for="(item, i) in dropdownList"
              :key="i"
              :command="item.value"
              >{{ item.text }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        ref="rightToolbar"
        :show-search.sync="showSearch"
        :columns="columnsList"
        @queryTable="getList"
      >
        <el-button
          type="primary"
          size="small"
          :loading="saveLoading"
          @click="saveColumnsList"
          >保存</el-button
        >
      </right-toolbar>
    </el-row>
    <el-table
      id="table_excel"
      ref="table"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :summary-method="getSummaries"
      show-summary
      border
      @header-dragend="handleResize"
    >
      <el-table-column type="selection" width="50" fixed="left" />
      <el-table-column type="index" width="50" align="center" />
      <template v-for="(item, i) in queryData">
        <el-table-column
          v-if="item.ifHide === false"
          :key="i"
          :label="item.columnComment"
          align="center"
          :prop="item.columnComment"
          :show-overflow-tooltip="true"
          :width="item.javaField || ''"
          :sortable="item.ifSort"
        >
          <template #default="{ row }">
            <div
              :class="{ active: item.example }"
              @click="
                pathChange(item.example, row[item.columnComment], item, row)
              "
            >
              <dict-tag
                v-if="isDict(item.columnComment)"
                :type="isDict(item.columnComment)"
                :value="row[item.columnComment]"
              />
              <span v-else-if="isDateTime(item.columnComment)">{{
                parseData(row[item.columnComment])
              }}</span>
              <span v-else>{{ row[item.columnComment] }}</span>
            </div>
          </template>
        </el-table-column></template
      >
    </el-table>

    <!-- 分页组件  -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pageNo"
      :limit.sync="pageSize"
      @pagination="handleSearch"
    />
  </div>
</template>
<script>
import * as QueryManageApi from "@/api/mes/queryManage";
export default {
  name: "MocsQueryForm",
  components: {
    SearchBar: () => import("@/components/SearchBar"),
  },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 显隐列参数
      columnsList: [],
      // 保存加载层
      saveLoading: false,
      exportLoading: false,
      title: "",
      visible: false,
      // 所有的查询/产看条件
      queryData: [],
      // 所有的查询条件
      searchData: [],
      // 已添加的查询条件
      queryList: [],
      // 设置查询条件弹框中的数据
      querySetList: [],
      // 设置查询条件弹框中添加查询条件的值
      querySettingKey: "",
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 物料及产品列表列表
      list: [],
      // 查询参数
      pageNo: 1,
      pageSize: 20,
      sql: "",
      queryParams: {},
      headerWidthChange: false,
      dropdownList: [],
      dataSourceConfigId: null,
    };
  },
  watch: {
    $route: function (to, from) {
      // 获取显隐列列表
      this.id = this.$route.query?.id;
      this.getQueryData();
      QueryManageApi.queryManageExecutecomplexdropdownlist().then((res) => {
        this.dropdownList = res;
      });
    },
    visible(nVal) {
      if (nVal) {
        this.querySetList = JSON.parse(JSON.stringify([...this.queryList]));
      }
    },
  },
  created() {
    // 获取显隐列列表
    this.id = this.$route.query?.id;
    this.getQueryData();
    // 昱懋的，应该用不上
    /* QueryManageApi.queryManageExecutecomplexdropdownlist().then((res) => {
      this.dropdownList = res;
    });*/
  },
  beforeDestroy() {
    if (this.headerWidthChange) {
      this.headerWidthChange = false;
      const widthList = [];
      const headers = this.$refs.table.$el.querySelectorAll(
        ".el-table__header-wrapper tr th"
      );
      const queryData = this.queryData.filter((item) => {
        return !item.ifHide;
      });
      // console.log(queryData);
      headers.forEach((header, i) => {
        const width = header.offsetWidth;
        if (i !== 0 && headers.length - 1 !== i) {
          widthList.push({ id: queryData[i - 1].id, javaField: width });
        }
      });
      // console.log(widthList);
      QueryManageApi.updateWidth(widthList);
    }
  },
  methods: {
    // 小数点问题处理
    getHandleNumber(val) {
      return Math.round(parseFloat(val) * 100000000) / 100000000;
    },
    // 数量合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        const values = this.list.map((item) => Number(item[column.property]));
        // console.log(column,values);
        if (this.isNumber(column.property)) {
          sums[index] = values.reduce((acc, cur) => {
            const value = Number(cur);
            if (!isNaN(value)) {
              return this.getHandleNumber(acc + cur);
            } else {
              return acc;
            }
          }, 0);
          sums[index];
        }
      });
      return sums;
    },
    saveColumnsList(e) {
      this.saveLoading = true;
      const list = this.columnsList.map((item) => {
        const { id, visible } = item;
        return { id, ifHide: !visible };
      });
      QueryManageApi.updateWidth(list)
        .then(() => {
          this.$refs.rightToolbar.open = false;
          this.getQueryData();
        })
        .finally(() => {
          this.saveLoading = false;
        });
    },
    async getQueryList() {
      try {
        this.loading = true;
        // const res = await SaleOrderApi.getSaleOrderPage(this.queryParams);
        // this.list = res.data.list;
        // this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    handleResize() {
      this.headerWidthChange = true;
    },
    pathChange(path, val, item, row) {
      // console.log(path);
      if (path) {
        console.log(val, item, row);
        let url = `${path}`;
        if (item) {
          url =
            url +
            "&columnComment=" +
            item.columnComment +
            "&value=" +
            row[item.columnComment];
        }
        this.$router.push({ path: url });
      }
    },
    // 批量操作
    async batchCommand(url) {
      const list = this.$refs.table.selection;
      if (list.length === 0) {
        return this.$message.warning(`请选择需要批量操作的订单！`);
      }
      try {
        await this.$modal.confirm(`您正在进行批量操作，请确认是否继续?`);
        const baseUrl = url.replace("/admin-api", ""); // 去掉 /admin-api
        await QueryManageApi.batchApi(baseUrl, list);
        this.$message.success(`批量操作成功`);
      } catch {
      } finally {
        this.handleQuery();
      }
    },
    Export() {
      this.$confirm("确定要导出文件到Excel?", "导出提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }).then(() => {
        setTimeout(() => {
          var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
          const tables = document.getElementById("table_excel"); // 这里是绑定元素，输入你要导出的table表格的id
          const table_book = this.$XLSX.utils.table_to_book(tables, xlsxParam);
          const table_write = this.$XLSX.write(table_book, {
            bookType: "xlsx",
            bookSST: true,
            type: "array",
          });
          try {
            this.$FileSaver.saveAs(
              new Blob([table_write], { type: "application/octet-stream" }),
              `${this.title}.xlsx` // 这里是文件名
            );
          } catch (e) {
            if (typeof console !== "undefined") {
              // console.log(e, table_write);
            }
          }
          return table_write;
        }, 1000);
      });
    },
    async ExportAll() {
      await this.$modal.confirm("是否确认导出所有查询数据项?");
      try {
        const list = [];
        const paramList = this.queryList.forEach((item) => {
          let { key, operate, value } = item;
          value = (value || "").toString();
          if (item.dataType === "ym_date_query_type") {
            operate = "between";
          }
          list.push({ key, operate, value });
        });
        // return
        this.exportLoading = true;
        const res = await QueryManageApi.exportExcel({
          id: this.id,
          paramList: list,
        });
        this.$download.excel(res, this.title);
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    // 确定修改查询条件
    queryDataSetOk() {
      this.queryList = JSON.parse(JSON.stringify([...this.querySetList]));
      this.visible = false;
    },
    // 查询条件下拉修改
    queryKeyChange(e, i, type) {
      const { dataType, htmlType, dictType } = this.searchData.find(
        (item) => item.columnName === e
      );
      if (type === "query") {
        this.queryList[i].dataType = dataType;
        this.queryList[i].htmlType = htmlType;
        this.queryList[i].dictType = dictType;
        this.queryList[i].operate =
          dataType == "ym_string_query_type" ? "like" : "";
      }
      if (type === "querySet") {
        this.querySetList[i].dataType = dataType;
        this.querySetList[i].htmlType = htmlType;
        this.querySetList[i].dictType = dictType;
        this.querySetList[i].operate =
          dataType == "ym_string_query_type" ? "like" : "";
      }
      // console.log(dataType, htmlType, dictType);
    },
    // 判断table中的数据是否为字典数据
    isDict: function (key) {
      let isDict = false;
      this.queryData.some((item) => {
        if (item.columnComment == key) {
          if (item.dictType) {
            isDict = item.dictType;
          }
          return true;
        }
        return false;
      });
      return isDict;
    },
    // 判断table中的数据字段类型是否为数值 ym_int_query_type
    isNumber: function (key) {
      let isNum = false;
      this.queryData.some((item) => {
        if (item.columnComment == key) {
          if (item.dataType === "ym_int_query_type") {
            isNum = true;
          }
          return true;
        }
        return false;
      });
      return isNum;
    },
    // 判断table中的数据是否为时间
    isDateTime: function (key) {
      let isDateTime = false;
      this.queryData.some((item) => {
        if (item.columnComment == key) {
          if (item.javaType === "LocalDateTime") {
            isDateTime = true;
          }
          return true;
        }
        return false;
      });
      return isDateTime;
    },
    parseData(val) {
      if (!val) {
        return "";
      }
      var date = new Date(val); // 时间戳转换成Date对象
      return date.toISOString().slice(0, 10); // 格式化为YYYY-MM-DD
    },
    // 设置查询条件 删除
    delQueryItem(i) {
      this.querySetList.splice(i, 1);
    },
    // 设置查询条件修改查询条件下拉 添加
    querySettingKeyChange(e) {
      if (this.querySetList.length === this.searchData.length) {
        return;
      }
      const { dataType, htmlType, dictType } = this.searchData.find(
        (item) => item.columnName === e
      );
      this.querySettingKey = "";
      this.querySetList.push({
        dataType,
        htmlType,
        dictType,
        key: e,
      });
    },
    /** 获取查询列表 */
    async getQueryData() {
      this.loading = true;
      // 执行查询
      const res = await QueryManageApi.getQueryManageColumnListByMasterId(
        this.id
      );
      // console.log(res.data,'==========');
      this.queryData = res.data;
      this.columnsList = res.data.map((item, i) => {
        const { columnComment, id, ifHide } = item;
        return { key: i, label: columnComment, id, visible: !ifHide };
      });
      this.searchData = res.data.filter((item) => {
        return item.listOperationResult && item.ifHide === false;
      });
      // console.log(this.searchData);
      this.queryList = [];
      for (let i = 0; i < 2; i++) {
        if (!this.searchData[i]) {
          break;
        }
        const { dataType, htmlType, dictType, columnName } = this.searchData[i];
        this.queryList.push({
          dataType,
          htmlType,
          dictType,
          key: columnName,
          operate: dataType == "ym_string_query_type" ? "like" : "",
        });
      }

      if (this.$route.query?.columnComment) {
        let key = "";
        this.searchData.filter((v) => {
          if (v.columnComment === this.$route.query?.columnComment) {
            key = v.columnName;
          }
        });
        if (key) {
          this.queryList.push({
            key: key,
            operate: "=",
            value: this.$route.query?.value,
          });
        }
      }
      const res1 = await QueryManageApi.getQueryManage(this.id);
      this.title = res1.data.name;
      this.sql = res1.data.sqlStatement;
      this.dataSourceConfigId = res1.data?.dataSourceConfigId;
      this.getList();
      this.loading = false;
    },
    getList() {
      this.loading = true;
      const paramList = this.queryList.map((item) => {
        let { key, operate, value } = item;
        value = (value || "").toString();
        if (item.dataType === "ym_date_query_type") {
          operate = "between";
        }
        return { key, operate, value };
      });
      QueryManageApi.loadTableData({
        // sql: this.sql,
        id: this.id,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        paramList,
        dataSourceConfigId: this.dataSourceConfigId,
      })
        .then((res) => {
          this.list = res.data.list;
          this.total = res.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSearch() {
      this.list = [];
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作  */
    resetQuery() {
      this.queryList.forEach((item, i) => {
        // this.queryList[i].value = null;
        this.$set(this.queryList[i], "value", null);
      });
      this.handleQuery();
    },
  },
};
</script>
<style lang="scss" scoped>
.mb8 {
  margin-bottom: 0;
}

.app-container {
  margin: 8px;
  padding: 0;
  // height: calc(100vh - 100px);
  padding-bottom: 20px;
}

::v-deep .el-form-item {
  margin-bottom: 0px !important;
}

::v-deep .el-tabs__item {
  height: 30px !important;
  line-height: 30px !important;
  padding: 0 15px !important;
}

::v-deep .el-tabs--border-card > .el-tabs__content {
  padding: 2px !important;
}

::v-deep .pagination-container {
  margin: 0;
  padding: 0;
}

.active {
  color: #1890ff !important;
}

.active:hover {
  cursor: pointer;
}
</style>
