<template>
  <div>
    <mega-table-query-filter
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      @query="handleQuery"
      @reset="handleReset"
    />
    <a-collapse
      default-active-key="a"
      expand-icon-position="right"
      class="collapse-header-divide"
      style="border-top: 8px solid #f0f2f5 !important"
    >
      <a-collapse-panel key="a" :header="$t('MAINTENANCE_REPORT')">
        <div class="maintain-report px-4 pb-4">
          <div class="maintain-report_content px-4 py-2">
            <div
              v-for="(item, index) in contentItems"
              :key="index"
              class="content-item py-2"
            >
              <span class="content-item_label mr-2">{{ $t(item.label) }}:</span>
              <span class="content-item_value">{{ item.value }}</span>
            </div>
          </div>
        </div>
      </a-collapse-panel>
    </a-collapse>
    <a-collapse
      default-active-key="b"
      expand-icon-position="right"
      class="collapse-header-divide"
    >
      <a-collapse-panel key="b" :header="$t('MAINTENANCE_DESC')">
        <MomTable
          ref="MomTable"
          row-key="id"
          :columns="tableColumns"
          :data-source="dataSource"
          :action-buttons="actionButtons"
          :show-util-operator="false"
          :total="total"
          :page.sync="page"
          :row-class-name="isRedRow"
          @search="search"
          @edit="handleEdit"
        >
          <div slot="status" slot-scope="text, record">
            <div
              class="status-box mt-2 flex justify-center items-center"
              :class="{
                'is-doing': record.status === 'EXECUTING',
                'is-expired': record.status === 'OVERDUE',
                'is-end': record.status === 'ALREADY_FINISH',
              }"
            >
              {{ formatData(statusList, record.status) }}
            </div>
          </div>
        </MomTable>
      </a-collapse-panel>
    </a-collapse>
  </div>
</template>

<script>
import { uniqBy } from "lodash";
import moment from "moment";
import { TableQueryFilter as MegaTableQueryFilter } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { exportExcel } from "@/utils";
import SelectSearch from "@/components/epms/SelectSearch";

export default {
  components: { MegaTableQueryFilter },
  data() {
    return {
      contentItems: [
        {
          code: "totalCount",
          label: "MAINTENANCE_TASKSUM",
          value: 0,
        },
        {
          code: "expireCount",
          label: "OVERDUE_TASKSQTY",
          value: 0,
        },
        {
          code: "finishCount",
          label: "COMPLETED_TASKSQTY",
          value: 0,
        },
        {
          code: "expireUser",
          label: "MAINTENANCE_OVERDUE_STAFF",
          value: "",
        },
      ],
      loading: false, // 表格loading
      // 查询的表单的配置项
      queryForm: {
        frmIdList: [],
        responsibleUserList: [],
        status: [],
        dateArr: [],
      },
      startTime: "",
      endTime: "",
      isFirst: true,
      page: 1,
      total: 0,
      actionButtons: [
        (h, { record, index }) =>
          this.hasAuth("EPMS:MAINTENANCE_REPORT:EDIT") &&
          record.status === "ALREADY_FINISH" && (
            <span
              class="text-primary cursor-pointer"
              title={this.$t("EDIT")}
              onClick={() => this.handleEdit(record)}
            >
              <a-icon type="edit" />
            </span>
          ),
        (h, { record, index }) =>
          record.status === "ALREADY_FINISH" && (
            <span
              class="cursor-pointer"
              title={this.$t("VIEW")}
              onClick={() => this.handlePreview(record, index)}
            >
              <a-icon type="eye" />
            </span>
          ),
        (h, { record, index }) =>
          record.status === "ALREADY_FINISH" && (
            <span
              class="cursor-pointer"
              title={this.$t("DOWNLOAD")}
              onClick={() => this.handleDownlaod(record)}
            >
              <a-icon type="download" />
            </span>
          ),
      ],
      dataSource: [],
      drawerVisible: false,
      form: {
        id: null,
        errorCodeType: "",
        errorCategoryName: "",
      },
      statusList: [],
      isReset: false, // 是否重置SelectSearch组件value
    };
  },
  computed: {
    // 表格搜索配置
    queryFormItem() {
      return this.$observable("queryFormItem", {
        frmIdList: {
          itemType: "custom",
          label: () => this.$t("MAINTENANCE_FORM_NAME"),
          customRender: () => {
            return (
              <SelectSearch
                show-multiple={true}
                request-api={"/api/epm/pmm/pm-frm/search?enableFlag=Y"}
                option-label={"pmFrmName"}
                query-list-key="searchKey"
                isReset={this.isReset}
                placeholder={
                  this.$t("PLACESELECT") + this.$t("MAINTENANCE_FORM_NAME")
                }
                onChange={this.onSelectSearchChangeForm}
              />
            );
          },
        },
        responsibleUserList: {
          itemType: "custom",
          label: () => this.$t("LEADER_NAME"),
          customRender: () => {
            return (
              <SelectSearch
                show-multiple={true}
                request-api={"/api/mdm/user/search-with-site"}
                option-label={"name"}
                query-list-key="userName"
                search-params={{ enableFlag: "Y" }}
                isReset={this.isReset}
                placeholder={this.$t("PLACESELECT") + this.$t("LEADER_NAME")}
                onChange={this.onSelectSearchChangeUser}
              />
            );
          },
        },
        status: {
          itemType: "custom",
          label: () => this.$t("TASK") + this.$t("STATUS"),
          customRender: () => {
            const selectOptionItems = this.statusList.map((v, index) => {
              return (
                <a-select-option value={v.value} key={v.value}>
                  {v.label}
                </a-select-option>
              );
            });
            return (
              <a-select
                value={this.queryForm.status}
                mode={"multiple"}
                filterOption={this.filterOption}
                allowClear={true}
                placeholder={
                  this.$t("PLACESELECT") + this.$t("TASK") + this.$t("STATUS")
                }
                onChange={(e) => {
                  this.queryForm.status = e;
                }}
              >
                {selectOptionItems}
              </a-select>
            );
          },
        },
        dateArr: {
          itemType: "custom",
          label: () => this.$t("DATE"),
          customRender: () => {
            return (
              <div class={"flex"}>
                <a-date-picker
                  style={"width: 48%"}
                  allowClear={false}
                  disabledDate={this.disabledStartDate}
                  v-model={this.startTime}
                  onChange={() => {
                    this.changeStartTime();
                  }}
                />
                <span>~</span>
                <a-date-picker
                  style={"width: 48%"}
                  allowClear={false}
                  disabledDate={this.disabledEndDate}
                  v-model={this.endTime}
                  onChange={() => {
                    this.changeEndTime();
                  }}
                />
              </div>
            );
          },
        },
      });
    },
    tableColumns() {
      return this.$observable("tableColumns", [
        {
          dataIndex: "pmFrmCode", // 任务对应表单编码
          title: () => `${this.$t("EPMS_TASK_CORRESPOND_FORM_CODE")}`,
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "pmFrmName", // 任务对应表单名称
          title: () => `${this.$t("TASK_CORRESPOND_FORM_NAME")}`,
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "pmEqpName", // 保养对象
          title: () => `${this.$t("MAINTENANCE_OBJECT")}`,
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "planEndTime", // 计划执行完成时间
          title: () =>
            `${this.$t("PLAN")}${this.$t("TODO")}${this.$t("COMPLETE_TIME")}`,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "responsibleName", // 负责人
          title: () => `${this.$t("LEADER_NAME")}`,
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "status", // 任务状态
          title: () => `${this.$t("TASK")}${this.$t("STATUS")}`,
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "status" },
        },
        {
          dataIndex: "finishTime", // 保养完成时间
          title: () =>
            `${this.$t("MAINTENANCE_TASK")}${this.$t("COMPLETE_TIME")}`,
          ellipsis: true,
          width: 200,
        },
      ]);
    },
  },
  created() {
    this.startTime = moment(new Date()).format("YYYY-MM-DD");
    this.endTime = moment(new Date()).format("YYYY-MM-DD");
    this.init();
  },
  methods: {
    // 获取返回数据，点检表单
    onSelectSearchChangeForm(e, list) {
      this.isReset = false;
      this.queryForm.frmIdList = list.join(",");
    },
    // 获取返回数据，点检表单
    onSelectSearchChangeUser(e, list, info) {
      this.isReset = false;
      this.queryForm.responsibleUserList = info
        .map((item) => item.userName)
        .join(",");
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text
        .toLowerCase()
        .includes(input.toLowerCase());
    },
    changeStartTime() {
      if (this.isFirst) {
        this.endTime = "";
        this.isFirst = false;
      }
    },
    changeEndTime() {
      if (this.isFirst) {
        this.startTime = "";
        this.isFirst = false;
      }
    },
    disabledStartDate(startValue) {
      const toDay = new Date().getTime();
      if (!this.endTime) {
        return startValue.valueOf() >= toDay;
      }
      const endValue = moment(this.endTime);
      const yearAfterStart = moment(
        new Date(startValue).setFullYear(new Date(startValue).getFullYear() + 1)
      );
      return (
        startValue.valueOf() > endValue.valueOf() ||
        startValue.valueOf() >= toDay ||
        yearAfterStart.valueOf() <= endValue.valueOf()
      );
    },
    disabledEndDate(endValue) {
      const toDay = new Date().getTime();
      if (!this.startTime) {
        return endValue.valueOf() >= toDay;
      }
      const startValue = moment(this.startTime);
      const yearAfterStart = moment(
        new Date(startValue).setFullYear(new Date(startValue).getFullYear() + 1)
      );
      return (
        startValue.valueOf() > endValue.valueOf() ||
        endValue.valueOf() >= toDay ||
        yearAfterStart.valueOf() <= endValue.valueOf()
      );
    },
    // 初始化数据
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PM_STATUS`
        ), // 保养状态
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/epm/ebs/report-switch-config/get-batch`,
          {
            params: {
              reportKeyList:
                "PM_ANALYSIS",
            },
          }
        ), // 是否显示配置详情
      ]).then(([pmStatus, switchConfigRes]) => {
        this.statusList = pmStatus.data?.data;
      });
    },
    // 字典表匹配数据
    formatData(data, status) {
      const result = data.find((item) => item.value === status?.toString());
      return result ? result.label : "";
    },
    isRedRow(record) {
      let tempStr = "";
      if (record.overdueFlag === "Y") {
        tempStr += "redFlag";
      }
      return tempStr;
    },
    // 查询
    handleQuery() {
      this.page = 1;
      this.$refs.MomTable?.query();
    },
    // 重置
    handleReset() {
      this.queryForm.frmIdList = [];
      this.queryForm.responsibleUserList = [];
      this.queryForm.status = [];
      this.isReset = true;
      this.startTime = moment(new Date()).format("YYYY-MM-DD");
      this.endTime = moment(new Date()).format("YYYY-MM-DD");
      this.page = 1;
      this.$refs.MomTable?.query();
    },
    // 查询方法
    search(params) {
      const { frmIdList, responsibleUserList, status } = this.queryForm;
      const options = {
        frmIdList,
        responsibleUserList,
        statusList: status.join(),
        startTime: this.startTime
          ? moment(this.startTime).format("YYYY-MM-DD")
          : "",
        endTime: this.endTime ? moment(this.endTime).format("YYYY-MM-DD") : "",
      };
      const searchParams = {
        ...params,
        ...options,
      };
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-task-rpt/search`, {
          params: searchParams,
        })
        .then((res) => {
          this.dataSource = res.data.data.records;
          this.total = res.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-task-rpt/count`, {
          params: searchParams,
        })
        .then((res) => {
          const reportData = res.data.data;
          this.contentItems = this.contentItems.map((item) => {
            // eslint-disable-next-line no-param-reassign
            item.value = reportData[item.code];
            return item;
          });
        });
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.$router.push({
        query: {
          id: row.id,
        },
        path: "/eam/eqp_maintain/maintenance_report/edit",
      });
    },
    // 点击表格行内的预览
    handlePreview(row) {
      this.$router.push({
        query: {
          id: row.id,
        },
        path: "/eam/eqp_maintain/maintenance_report/preview",
      });
    },
    handleDownlaod(row) {
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-task-rpt/detail-export?id=${row.id}`,
        method: "get",
        responseType: "blob",
      }).then((res) => {
        const filename = `${this.$t("MOLD")}${this.$t(
          "MAINTENANCE_REPORT"
        )}.xlsx`;
        exportExcel(res.data, decodeURI(filename));
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/status_epms.less";
.maintain-report {
  &_title {
    font-size: 1.125rem;
    line-height: 2.5rem;
  }
  &_content {
    display: flex;
    flex-flow: row wrap;
    justify-content: flex-start;
    align-items: center;
    .content-item {
      flex: 0 0 33.3%;
      font-size: 1rem;
      &_label {
        color: #333;
      }
      &_value {
        color: #666;
      }
    }
  }
}
.result-value.isError {
  color: #f00;
}
/deep/ .ant-table-row.redFlag {
  background-color: rgba(255, 0, 0, 0.12) !important;
}
</style>
