<template>
  <div>
    <a-tabs
      v-model="tabActiveKey"
      default-active-key="tabActiveKey"
      style="border-top: 8px solid rgb(240, 242, 245) !important"
      @change="handleTabChange"
    >
      <a-tab-pane key="a" :tab="$t('SPOT_CHECK')"></a-tab-pane>
      <a-tab-pane key="b" :tab="$t('PATROL')"></a-tab-pane>
    </a-tabs>
    <a-collapse
      default-active-key="c"
      expand-icon-position="right"
      class="collapse-header-divide"
    >
      <a-collapse-panel key="c" :header="$t('CHECK_REPORT')">
        <mega-table-query-filter
          v-if="tabActiveKey === 'a'"
          :query-param="queryForm"
          :query-param-item="queryFormItem"
          @query="handleQuery"
          @reset="handleReset"
        />
        <mega-table-query-filter
          v-if="tabActiveKey === 'b'"
          :query-param="queryFormSec"
          :query-param-item="queryFormItemSec"
          @query="handleQuery"
          @reset="handleReset"
        />
      </a-collapse-panel>
    </a-collapse>
    <a-collapse
      default-active-key="a"
      expand-icon-position="right"
      class="collapse-header-divide"
    >
      <a-collapse-panel key="a" :header="$t('CHECK_REPORT')">
        <div v-if="tabActiveKey === 'a'" class="check-report px-4 pb-4">
          <div class="check-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>
        <div v-if="tabActiveKey === 'b'" class="check-report px-4 pb-4">
          <div class="check-report_content px-4 py-2">
            <div
              v-for="(item, index) in contentItemsSec"
              :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('CHECK_DESC')">
        <MomTable
          v-show="tabActiveKey === 'a'"
          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>
          <div slot="resultValue" slot-scope="text, record">
            <span class="result-value" :class="{ isError: text === 'ERROR' }">
              {{ formatData(resultList, record.resultValue) }}
            </span>
          </div>
        </MomTable>
        <MomTable
          v-show="tabActiveKey === 'b'"
          ref="MomTableSec"
          row-key="id"
          :columns="tableColumnsSec"
          :data-source="dataSourceSec"
          :action-buttons="actionButtonsSec"
          :show-util-operator="false"
          :total="totalSec"
          :page.sync="pageSec"
          :row-class-name="isRedRow"
          @search="searchSec"
        >
          <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>
          <div slot="resultValue" slot-scope="text, record">
            <span class="result-value" :class="{ isError: text === 'ERROR' }">
              {{ formatData(resultList, record.resultValue) }}
            </span>
          </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 { Icon } from "ant-design-vue";
import ApiConstant from "@/api/ApiConstant";
import { exportExcel } from "@/utils";
import SelectSearch from "@/components/epms/SelectSearch";

export default {
  components: {
    MegaTableQueryFilter,
    // eslint-disable-next-line vue/no-unused-components
    SelectSearch,
  },
  data() {
    return {
      tabActiveKey: "a",
      contentItems: [
        {
          code: "totalCount",
          label: "CHECK_TASKSUM",
          value: 0,
        },
        {
          code: "expireCount",
          label: "OVERDUE_TASKSQTY",
          value: 0,
        },
        {
          code: "finishCount",
          label: "COMPLETED_TASKSQTY",
          value: 0,
        },
        {
          code: "ngCount",
          label: "ABNORMAL_TASKSQTY",
          value: 0,
        },
        {
          code: "expireUser",
          label: "CHECK_OVERDUE_STAFF",
          value: "",
        },
      ],
      contentItemsSec: [
        {
          code: "totalCount",
          label: "CHECK_TASKSUM",
          value: 0,
        },
        {
          code: "expireCount",
          label: "OVERDUE_TASKSQTY",
          value: 0,
        },
        {
          code: "finishCount",
          label: "COMPLETED_TASKSQTY",
          value: 0,
        },
        {
          code: "ngCount",
          label: "ABNORMAL_TASKSQTY",
          value: 0,
        },
        {
          code: "expireUser",
          label: "CHECK_OVERDUE_STAFF",
          value: "",
        },
      ],
      loading: false, // 表格loading
      // 查询的表单的配置项
      queryForm: {
        frmIdList: "",
        responsibleUserList: "",
        status: [],
        dateArr: [],
      },
      startTime: "",
      endTime: "",
      isFirst: true,
      queryFormSec: {
        frmIdListSec: "",
        dateArrSec: [],
      },
      startTimeSec: "",
      endTimeSec: "",
      page: 1,
      pageSec: 1,
      total: 0,
      totalSec: 0,
      actionButtons: [
        (h, { record, index }) =>
          this.hasAuth("EPMS:CHECK_REPORT:EDIT") &&
          record.status === "ALREADY_FINISH" && (
            <Icon
              type="edit"
              title={this.$t("EDIT")}
              onClick={() => this.handleEdit(record)}
            />
          ),
        (h, { record, index }) =>
          record.status === "ALREADY_FINISH" && (
            <Icon
              class="text-primary cursor-pointer"
              type="eye"
              title={this.$t("VIEW")}
              onClick={() => this.handlePreview(record)}
            />
          ),
        (h, { record, index }) =>
          record.status === "ALREADY_FINISH" && (
            <Icon
              class="text-primary cursor-pointer"
              type="download"
              title={this.$t("DOWNLOAD")}
              onClick={() => this.handleDownlaod(record)}
            />
          ),
      ],
      actionButtonsSec: [
        (h, { record, index }) => (
          <Icon
            type="eye"
            class="text-primary cursor-pointer"
            title={this.$t("VIEW")}
            onClick={() => this.handlePreviewSec(record)}
          />
        ),
      ],
      dataSource: [],
      dataSourceSec: [],
      drawerVisible: false,
      form: {
        id: null,
        errorCodeType: "",
        errorCategoryName: "",
      },
      statusList: [],
      resultList: [],
      isReset: false, // 是否重置SelectSearch组件value
    };
  },
  computed: {
    // 表格搜索配置
    queryFormItem() {
      return this.$observable("queryFormItem", {
        frmIdList: {
          itemType: "custom",
          label: () => this.$t("CHECK_FORM_NAME"),
          customRender: () => {
            return (
              <SelectSearch
                key={"frmId"}
                show-multiple={true}
                request-api={"/api/epm/pcm/pc-frm/search?enableFlag=Y"}
                option-label={"pcFrmName"}
                query-list-key="searchKey"
                isReset={this.isReset}
                placeholder={
                  this.$t("PLACESELECT") + this.$t("CHECK_FORM_NAME")
                }
                onChange={this.onSelectSearchChangeForm}
              />
            );
          },
        },
        responsibleUserList: {
          itemType: "custom",
          label: () => this.$t("RESPONSIBLE_USER"),
          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("RESPONSIBLE_USER")
                }
                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>
            );
          },
        },
      });
    },
    queryFormItemSec() {
      return this.$observable("queryFormItemSec", {
        frmIdListSec: {
          itemType: "custom",
          label: () => this.$t("CHECK_FORM_NAME"),
          customRender: () => {
            return (
              <SelectSearch
                key={"sec"}
                show-multiple={true}
                request-api={"/api/epm/pcm/pc-frm/search?enableFlag=Y"}
                option-label={"pcFrmName"}
                query-list-key="searchKey"
                isReset={this.isReset}
                placeholder={
                  this.$t("PLACESELECT") + this.$t("CHECK_FORM_NAME")
                }
                onChange={this.onSelectSearchChangeFormSec}
              />
            );
          },
        },
        dateArrSec: {
          itemType: "custom",
          label: () => this.$t("DATE"),
          customRender: () => {
            return (
              <div class={"flex"}>
                <a-date-picker
                  style={"width: 48%"}
                  allowClear={false}
                  disabledDate={this.disabledStartDateSec}
                  v-model={this.startTimeSec}
                  onChange={() => {
                    this.changeStartTimeSec();
                  }}
                />
                <span>~</span>
                <a-date-picker
                  style={"width: 48%"}
                  allowClear={false}
                  disabledDate={this.disabledEndDateSec}
                  v-model={this.endTimeSec}
                  onChange={() => {
                    this.changeEndTimeSec();
                  }}
                />
              </div>
            );
          },
        },
      });
    },
    tableColumns() {
      return this.$observable("tableColumns", [
        {
          dataIndex: "pcFrmCode", // 任务对应表单编码
          title: () => `${this.$t("EPMS_TASK_CORRESPOND_FORM_CODE")}`,
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "pcFrmName", // 任务对应表单名称
          title: () => `${this.$t("TASK_CORRESPOND_FORM_NAME")}`,
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "pcObjectName", // 点检对象
          title: () => `${this.$t("CHECK_OBJECT")}`,
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "planEndTime", // 计划执行完成时间
          title: () =>
            `${this.$t("PLAN")}${this.$t("TODO")}${this.$t("COMPLETE_TIME")}`,
          ellipsis: true,
          width: 240,
        },
        {
          dataIndex: "responsibleName", // 负责人
          title: () => `${this.$t("RESPONSIBLE_USER")}`,
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "status", // 任务状态
          title: () => `${this.$t("TASK")}${this.$t("STATUS")}`,
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "status" },
        },
        {
          dataIndex: "resultId", // 点检结果
          title: () => `${this.$t("CHECK_RESULT")}`,
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "resultValue" },
        },
        {
          dataIndex: "finishTime", // 点检完成时间
          title: () => `${this.$t("CHECK_TASK")}${this.$t("COMPLETE_TIME")}`,
          ellipsis: true,
          // width: 200,
        },
      ]);
    },
    tableColumnsSec() {
      return this.$observable("tableColumnsSec", [
        {
          dataIndex: "pcFrmCode", // 任务对应表单编码
          title: () => `${this.$t("EPMS_TASK_CORRESPOND_FORM_CODE")}`,
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "pcFrmName", // 任务对应表单名称
          title: () => `${this.$t("TASK_CORRESPOND_FORM_NAME")}`,
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "pcObjectGroupName", // 巡检对象组
          title: () =>
            `${this.$t("PATROL")}${this.$t("OBJECT_GROUP")}${this.$t("NAME")}`,
          ellipsis: true,
          sorter: false,
        },
      ]);
    },
  },
  created() {
    this.startTime = moment(new Date()).format("YYYY-MM-DD");
    this.endTime = moment(new Date()).format("YYYY-MM-DD");
    this.startTimeSec = moment(new Date()).format("YYYY-MM-DD");
    this.endTimeSec = moment(new Date()).format("YYYY-MM-DD");
    this.init();
  },
  methods: {
    // 获取返回数据，点检表单
    onSelectSearchChangeForm(e, list) {
      this.isReset = false;
      this.queryForm.frmIdList = list.join(",");
    },
    onSelectSearchChangeFormSec(e, list) {
      this.isReset = false;
      this.queryFormSec.frmIdListSec = 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;
      }
    },
    changeStartTimeSec() {
      if (this.isFirst) {
        this.endTimeSec = "";
        this.isFirst = false;
      }
    },
    changeEndTimeSec() {
      if (this.isFirst) {
        this.startTimeSec = "";
        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()
      );
    },
    disabledStartDateSec(startValue) {
      const toDay = new Date().getTime();
      if (!this.endTimeSec) {
        return startValue.valueOf() >= toDay;
      }
      const endValue = moment(this.endTimeSec);
      const yearAfterStart = moment(
        new Date(startValue).setFullYear(new Date(startValue).getFullYear() + 1)
      );
      return (
        startValue.valueOf() > endValue.valueOf() ||
        startValue.valueOf() >= toDay ||
        yearAfterStart.valueOf() <= endValue.valueOf()
      );
    },
    disabledEndDateSec(endValue) {
      const toDay = new Date().getTime();
      if (!this.startTimeSec) {
        return endValue.valueOf() >= toDay;
      }
      const startValue = moment(this.startTimeSec);
      const yearAfterStart = moment(
        new Date(startValue).setFullYear(new Date(startValue).getFullYear() + 1)
      );
      return (
        startValue.valueOf() > endValue.valueOf() ||
        endValue.valueOf() >= toDay ||
        yearAfterStart.valueOf() <= endValue.valueOf()
      );
    },
    handleTabChange() {
      this.handleQuery();
    },
    // 初始化数据
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_STATUS`
        ), // 点检状态
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_RESULT`
        ), // 点检结果
      ]).then(([pcStatus, pcResults]) => {
        this.statusList = pcStatus.data?.data;
        this.resultList = pcResults.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.pageSec = 1;
      if (this.tabActiveKey === "a") {
        setTimeout(() => {
          this.$refs.MomTable?.query();
        }, 500);
      } else {
        setTimeout(() => {
          this.$refs.MomTableSec?.query();
        }, 500);
      }
    },
    // 重置
    handleReset() {
      this.isReset = true;
      this.isFirst = true;
      if (this.tabActiveKey === "a") {
        this.queryForm.frmIdList = "";
        this.queryForm.responsibleUserList = "";
        this.queryForm.status = [];
        this.startTime = moment(new Date()).format("YYYY-MM-DD");
        this.endTime = moment(new Date()).format("YYYY-MM-DD");
      } else {
        this.queryFormSec.frmIdListSec = "";
        this.startTimeSec = moment(new Date()).format("YYYY-MM-DD");
        this.endTimeSec = moment(new Date()).format("YYYY-MM-DD");
      }
      this.handleQuery();
    },
    // 查询方法
    search(params) {
      const { frmIdList, responsibleUserList, status } = this.queryForm;
      const options = {
        frmIdList,
        responsibleUserList,
        statusList: status.join(),
        startDate: this.startTime
          ? moment(this.startTime).format("YYYY-MM-DD")
          : "",
        endDate: this.endTime ? moment(this.endTime).format("YYYY-MM-DD") : "",
      };
      const searchParams = {
        ...params,
        ...options,
      };
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-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/pcm/pc-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;
          });
        });
    },
    searchSec(params) {
      const { frmIdListSec } = this.queryFormSec;
      const options = {
        frmIdList: frmIdListSec,
        // responsibleUserList,
        // statusList: status.join(),
        startDate: this.startTimeSec
          ? moment(this.startTimeSec).format("YYYY-MM-DD")
          : "",
        endDate: this.endTimeSec
          ? moment(this.endTimeSec).format("YYYY-MM-DD")
          : "",
      };
      const searchParams = {
        ...params,
        ...options,
        type: "INSPECTION",
      };
      this.loading = true;
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-task-rpt/search-by-inspect`,
          {
            params: searchParams,
          }
        )
        .then((res) => {
          this.dataSourceSec = res.data.data.records;
          this.totalSec = res.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-task-rpt/count`, {
          params: searchParams,
        })
        .then((res) => {
          const reportData = res.data.data;
          this.contentItemsSec = this.contentItemsSec.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,
          resultId: row.resultId,
        },
        path: "/eam/eqp_check/check_report/edit",
      });
    },
    // 点击表格行内的预览
    handlePreview(row) {
      this.$router.push({
        query: {
          id: row.id,
        },
        path: "/eam/eqp_check/check_report/preview",
      });
    },
    handleDownlaod(row) {
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-task-rpt/detail-export?id=${row.id}`,
        method: "get",
        responseType: "blob",
      }).then((res) => {
        const filename = `${this.$t("CHECK_REPORT")}.xlsx`;
        exportExcel(res.data, decodeURI(filename));
      });
    },
    handlePreviewSec(row) {
      this.$router.push({
        query: {
          id: row.id,
        },
        path: "/eam/eqp_check/patrol_check_report/preview",
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/status_epms.less";
.check-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>
