<template>
  <div class="box_main">
    <a-tabs default-active-key="1" @change="handleChangeTab">
      <a-tab-pane
        key="1"
        :tab="`${$t('PATROL')}${$t('PLAN')}${$t('LIST_DISPLAY')}`"
      />
      <a-tab-pane
        key="2"
        :tab="`${$t('PATROL')}${$t('PLAN')}${$t('CALENDAR')}`"
        force-render
      />
    </a-tabs>
    <!-- 卡片模式 开始 -->
    <div v-show="showMode === 'card'">
      <div class="card_list">
        <a-spin :spinning="loading">
          <full-calendar
            class="test-fc"
            first-day="1"
            locale="fr"
            :events="monthData"
            :lang="lang"
            @changeMonth="changeMonth"
            @eventClick="eventClick"
            @dayClick="dayClick"
            @moreClick="moreClick"
          ></full-calendar>
        </a-spin>
      </div>
    </div>
    <!-- 卡片模式 结束 -->
    <!-- 列表模式 开始 -->
    <MomTable
      v-show="showMode === 'list'"
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :query-param="queryParam"
      :query-param-item="queryParamItem"
      :columns="columns"
      :data-source="dataSource"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :mega-extend="{
        rowIndex: false,
      }"
      @beforeSearch="beforeSearch"
      @copy="handleCopy"
      @search="search"
      @edit="handleEdit"
      @delete="handleDelete"
    >
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('EPMS:PARTOL_CHECK_PLAN:ADD')"
          @click="handleAdd"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <MomCopyButton
          v-if="hasAuth('EPMS:PARTOL_CHECK_PLAN:ADD')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @copy="handleCopy"
        />
        <MomEditButton
          v-if="hasAuth('EPMS:PARTOL_CHECK_PLAN:EDIT')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @edit="handleEdit"
        />
        <a-button
          v-if="hasAuth('EPMS:PARTOL_CHECK_PLAN:BATCH_DISCONTINUE')"
          :disabled="selectedRowKeys.length === 0"
          @click="
            handleBatchDisabled(
              'N',
              'DISCONTINUE',
              'PLAN_DISCONTINUE_INFO',
              'OPERATION_SUCCESS'
            )
          "
        >
          <i class="iconfont icon-Group- text-error"></i>
          {{ $t("BATCH_DISCONTINUE") }}
        </a-button>
        <a-button
          v-if="hasAuth('EPMS:PARTOL_CHECK_PLAN:BATCH_DELETE')"
          :disabled="selectedRowKeys.length === 0"
          type="danger"
          ghost
          @click="handleBatchDelete"
        >
          <a-icon type="delete" />
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <div slot="pcPlanName" slot-scope="text, record">
        <span class="name_link" @click="handleView(record)">
          {{ record.pcPlanName }}
        </span>
      </div>
      <div slot="enableFlag" slot-scope="text, record">
        <span class="status-box" :class="'able' + text">{{
          formatData(stateList, record.enableFlag)
        }}</span>
      </div>
    </MomTable>
    <!-- 列表模式 结束 -->
    <MegaModal
      :visible="modalVisible"
      :centered="true"
      :mask-closable="false"
      :title="modalForm.title"
      :width="'1060px'"
      @cancel="modalVisible = false"
      @ok="modalVisible = false"
    >
      <MomTable
        row-key="id"
        :columns="columnsDetail"
        :data-source="detailList"
        :mega-extend="{ rowAction: false }"
        :show-util-operator="false"
        :auto-adaptive-width="false"
      >
        <div slot="status" slot-scope="text, record">
          <!-- <span class="status-box" :class="'able' + text">{{
            formatData(statusList, record.sattus)
          }}</span> -->
          <div
            class="btn_status mt-1 flex justify-center items-center"
            :class="{
              'is-doing': record.status === 'EXECUTING',
              'is-expired': record.status === 'OVERDUE',
              'is-end': record.status === 'ALREADY_FINISH',
            }"
          >
            {{ getAttrValue(statusList, record.status) }}
          </div>
        </div>
      </MomTable>
      <a-form-model
        v-if="false"
        ref="modalForm"
        :model="modalForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-row>
          <a-col :span="24">
            <a-form-model-item :label="`${$t('CHECK_FORM')}${$t('NAME')}`">
              {{ modalForm.pcFrmName }}
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="`${$t('CHECK_OBJECT')}${$t('NAME')}`">
              {{ modalForm.pcObjectName }}
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="`${$t('PLAN')}${$t('HANDLE_TIME')}`">
              {{ modalForm.planStartTime }} - {{ modalForm.planEndTime }}
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="`${$t('TASK')}${$t('STATUS')}`">
              <div
                class="btn_status mt-2 flex justify-center items-center"
                :class="{
                  'is-doing': modalForm.status === 'EXECUTING',
                  'is-expired': modalForm.status === 'OVERDUE',
                  'is-end': modalForm.status === 'ALREADY_FINISH',
                }"
              >
                {{ getAttrValue(statusList, modalForm.status) }}
              </div>
            </a-form-model-item>
          </a-col>
          <a-col v-if="modalForm.overdueFlag === 'Y'" :span="24">
            <a-form-model-item :label="`${$t('OVERDUE')}`">
              <span style="color: rgba(255, 0, 0, 1)">{{
                getAttrValue(yesNoList, modalForm.overdueFlag)
              }}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <template slot="footer">
        <a-button type="primary" @click="modalVisible = false">{{
          $t("CONFIRM")
        }}</a-button>
      </template>
    </MegaModal>
  </div>
</template>

<script>
import { uniqBy } from "lodash";
import { mapState } from "vuex";
import { Modal as MegaModal } from "@mega-design/ui-vue";
import { Icon } from "ant-design-vue";
import ApiConstant from "@/api/ApiConstant";
import MomCopyButton from "@/components/MomCopyButton";
import MomEditButton from "@/components/MomEditButton";
import FullCalendar from "@/components/fullcalendar";

export default {
  components: {
    FullCalendar,
    MegaModal,
    MomCopyButton,
    MomEditButton,
  },
  data() {
    return {
      showMode: "list",
      modalVisible: false,
      loading: false, // 表格loading
      confirmLoading: false,
      options: {
        allowDuplicateUploads: true,
        target: "/core/api/mom-file/update-one",
        testChunks: true,
        single: true,
        chunkSize: 10 * 1024 * 1024,
      },
      // 查询的表单的配置项
      queryParam: {
        pcPlanName: "",
        enableFlag: "",
      },
      columns: [
        {
          dataIndex: "pcPlanCode", // 巡检计划编码
          title: () =>
            `${this.$t("PATROL")}${this.$t("PLAN")}${this.$t("CODE")}`,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "pcPlanName", // 巡检计划名称
          title: () =>
            `${this.$t("PATROL")}${this.$t("PLAN")}${this.$t("NAME")}`,
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "pcPlanName" },
        },
        {
          dataIndex: "enableFlag", // 启用、禁用状态
          align: "left",
          sorter: false,
          ellipsis: true,
          width: 200,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy", // 更新人员
          sorter: false,
          ellipsis: true,
          title: () => this.$t("UPDATE_BY"),
        },
        {
          dataIndex: "updateTime", // 更新时间
          ellipsis: true,
          title: () => this.$t("UPDATE_TIME"),
        },
      ],
      columnsDetail: [
        {
          dataIndex: "pcFrmName", // 巡检表单名称
          sorter: false,
          title: () =>
            `${this.$t("PATROL")}${this.$t("FORM")}${this.$t("NAME")}`,
          ellipsis: true,
        },
        {
          dataIndex: "pcObjectGroupName", // 巡检计划编码
          sorter: false,
          title: () =>
            `${this.$t("PATROL")}${this.$t("OBJECT_GROUP")}${this.$t("NAME")}`,
          ellipsis: true,
        },
        {
          dataIndex: "pcObjectName", // 巡检计划编码
          sorter: false,
          title: () =>
            `${this.$t("PATROL")}${this.$t("OBJECT")}${this.$t("NAME")}`,
          ellipsis: true,
        },
        {
          dataIndex: "status", // 启用、禁用状态
          sorter: false,
          ellipsis: true,
          width: 100,
          title: () => this.$t("TASK") + this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "status" },
        },
        {
          dataIndex: "planStartTime", // 巡检开始时间
          sorter: false,
          title: () => `${this.$t("PLAN")}${this.$t("START_TIME")}`,
          ellipsis: true,
        },
        {
          dataIndex: "planEndTime", // 巡检结束时间
          sorter: false,
          title: () => `${this.$t("PLAN")}${this.$t("END_TIME")}`,
          ellipsis: true,
        },
      ],
      total: 0,
      page: 1,
      actionButtons: [
        this.hasAuth("EPMS:PARTOL_CHECK_PLAN:ADD") && "copy",
        this.hasAuth("EPMS:PARTOL_CHECK_PLAN:EDIT") && "edit",
        this.hasAuth("EPMS:PARTOL_CHECK_PLAN:DELETE") && "delete",
        (h, { record, index }) =>
          this.hasAuth("EPMS:PARTOL_CHECK_PLAN:DISCONTINUE") &&
          record.enableFlag === "Y" && (
            <Icon
              type="stop"
              title={this.$t("DISCONTINUE")}
              onClick={() =>
                this.handleStatus(
                  { status: "N", id: record.id },
                  "DISCONTINUE",
                  "PLAN_DISCONTINUE_INFO",
                  "OPERATION_SUCCESS"
                )
              }
            />
          ),
      ],
      dataSource: [],
      drawerVisible: false,
      form: {
        id: null,
        checkObjectCode: "",
        pcPlanName: "",
        type: "",
      },
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      yesNoList: [], // 是否列表
      statusList: [], // 类型列表
      stateList: [],
      year: new Date().getFullYear(), // 当前年
      month: new Date().getMonth(), // 当前月
      monthData: [],
      modalForm: {},
      detailList: [], // 详情列表
    };
  },
  computed: {
    ...mapState({
      lang: (state) => state.app.locale,
    }),
    rules() {
      return {
        pcPlanName: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        pcPlanName: {
          label: () =>
            `${this.$t("PATROL")}${this.$t("PLAN")}${this.$t("NAME")}`,
          placeholder: () => this.$t("ENTER_PATROL_PLAN_NAME_KEYWORD"),
        },
        enableFlag: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
          label: () => this.$t("PLAN_STATUS"),
          on: {
            change: () => {
              this.$forceUpdate();
            },
          },
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
          if (this.selectedRowKeys.length) {
            this.selectedRows = uniqBy(this.selectedRows.concat(selectedRows));
          } else {
            this.selectedRows = selectedRows;
          }
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.enableFlag === "N",
          },
        }),
      };
    },
  },
  created() {
    this.init();
  },
  methods: {
    // 监听tab切换事件
    handleChangeTab(e) {
      if (e === "1") {
        this.showMode = "list";
        setTimeout(() => {
          this.$refs.MomTable?.search();
        }, 500);
      } else {
        this.showMode = "card";
        setTimeout(() => {
          this.queryList();
        }, 500);
      }
    },
    // 选择月份
    changeMonth(start, end, current) {
      this.year = new Date(current).getFullYear();
      this.month = new Date(current).getMonth() + 1;
      if (this.showMode === "card") {
        this.queryList();
      }
    },
    // 点击事件
    eventClick(event, jsEvent, pos) {
      this.detailList = event.detailList;
      this.modalForm = {
        title: event.title,
      };
      this.modalVisible = true;
      // this.getPlanDetail(event.id, event.title);
    },
    // 点击当天
    dayClick(day, jsEvent) {},
    // 查看更多
    moreClick(day, events, jsEvent) {},
    queryList() {
      const params = {
        year: this.year,
        month: this.month,
        pcPlanName: this.queryParam.pcPlanName,
      };
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/plan/list-for-calendar-by-inspect`,
          {
            params,
          }
        )
        .then(({ data }) => {
          const { pcTaskCalendarList, pcTaskCalendarCountList } = {
            ...data?.data,
          };
          /* eslint-disable */
          if (pcTaskCalendarList.length > 0) {
            let tempObj;
            this.monthData = pcTaskCalendarList.map((item) => {
              switch (item.status) {
                case "WAIT_FINISH":
                  item.cssClass = "is-start";
                  break;
                case "EXECUTING":
                  item.cssClass = "is-doing";
                  break;
                case "ALREADY_FINISH":
                  item.cssClass = "is-end";
                  break;
              }
              if (item.overDueFlag === "Y") {
                item.cssClass = "is-expired";
              }
              // const countItem = pcTaskCalendarCountList.find(
              //   (ele) => ele.monthDay === item.monthDay
              // );
              // const { executingCount, expireCount, finishCount, waitCount } =
              //   countItem;
              // let tempNum = 0;
              // if (parseFloat(executingCount) > 0) {
              //   tempNum += 1;
              // }
              // if (parseFloat(expireCount) > 0) {
              //   tempNum += 1;
              // }
              // if (parseFloat(finishCount) > 0) {
              //   tempNum += 1;
              // }
              // if (parseFloat(waitCount) > 0) {
              //   tempNum += 1;
              // }
              tempObj = {
                id: item.id,
                type: "pc",
                start: item.yearDay,
                title: item.pcPlanName,
                pcFrmName: item.pcFrmName,
                cssClass: item.cssClass,
                detailList: item.detailList,
                pcObjectName: item.pcObjectGroupName,
                // executingCount: parseFloat(executingCount),
                // expireCount: parseFloat(expireCount),
                // finishCount: parseFloat(finishCount),
                // waitCount: parseFloat(waitCount),
                // countLength: tempNum,
              };
              return tempObj;
            });
          }
          /* eslint-enable */
        });
    },
    getPlanDetail(id, title) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-task/get-detail-by-id`,
          {
            params: {
              id,
              updateFlag: "N",
            },
          }
        )
        .then(({ data }) => {
          this.modalForm = {
            title,
            ...data.data,
            pcFrmName: data.data?.pcFrmExtBPO.pcFrmName,
          };
          this.modalVisible = true;
        });
    },
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:COMMON:WHETHER_CHAR`
        ), // 状态数据字典
        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:PLAN_STATUS`
        ), // 类型数据字典
      ]).then(([yesNoRes, statusRes, enableStatus]) => {
        this.yesNoList = yesNoRes.data?.data;
        this.statusList = statusRes.data?.data;
        this.stateList = enableStatus.data?.data;
        if (enableStatus.data?.data && enableStatus.data?.data.length > 0) {
          this.queryParam.enableFlag = enableStatus.data?.data[0].value;
        }
        const arr = [{ label: "全部", value: "" }];
        const list = enableStatus.data?.data || [];
        this.queryParamItem.enableFlag.options = [...arr, ...list];
      });
    },
    beforeSearch() {},
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 表格查询
    search(params) {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      const searchParams = {
        ...params,
        enableFlag: this.queryParam.enableFlag,
        type: "INSPECTION",
      };
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pcm/plan/search`, {
          params: searchParams,
        })
        .then((res) => {
          this.dataSource = res.data.data.records;
          this.total = res.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 监听新增点击事件
    handleAdd() {
      this.$router.push({
        path: "/eam/eqp_check/partol_check_plan/add",
      });
    },
    // 监听编辑点击事件
    handleCopy(row) {
      this.$router.push({
        path: "/eam/eqp_check/partol_check_plan/add",
        query: {
          id: row.id,
        },
      });
    },
    // 监听详情点击事件
    handleView({ id }) {
      this.$router.push({
        query: {
          id,
        },
        path: "/eam/eqp_check/partol_check_plan/view",
      });
    },
    // 监听编辑点击事件
    handleEdit({ id }) {
      this.$router.push({
        query: {
          id,
        },
        path: "/eam/eqp_check/partol_check_plan/edit",
      });
    },
    // 监听删除点击事件
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/epm/pcm/plan/${row.id}`)
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 监听批量删除点击事件
    handleBatchDelete() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning(this.$t("SELECT_ONE_DATA"));
        return;
      }
      const params = {
        ids: this.selectedRowKeys,
      };
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/epm/pcm/plan/delete-batch`,
              {
                data: params,
              }
            )
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 监听启用，禁用点击事件
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id } = record;
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/epm/pcm/plan/stop/${id}`)
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 监听批量禁用点击事件
    handleBatchDisabled(status, titleText, contentText, tips) {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning(this.$t("SELECT_ONE_DATA"));
        return;
      }
      const tempArr = [];
      this.dataSource.forEach((item) => {
        this.selectedRowKeys.forEach((ele) => {
          if (item.id === ele && item.enableFlag !== status) {
            tempArr.push(item);
          }
        });
      });
      if (tempArr.length < 1) {
        const content =
          status === "Y" ? "NO_DATA_TO_ENABLE" : "NO_DATA_TO_DISABLE";
        this.$confirm({
          title: this.$t(titleText),
          content: this.$t(content),
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "exclamation-circle",
          onOk: () => {},
        });
        return;
      }
      const params = {
        status,
        ids: this.selectedRowKeys,
      };
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/epm/pcm/plan/stop-batch`,
              params
            )
            .then(() => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/status_epms.less";
.name_link {
  color: rgba(14, 168, 208, 1);
  cursor: pointer;
  display: block;
}
.change_box {
  display: flex;
  justify-content: space-between;
  height: 32px;
  position: absolute;
  top: 95px;
  right: 15px;
  cursor: pointer;
  z-index: 999;
  .change_item {
    min-width: 98px;
    height: 100%;
    border-radius: 4px;
    background: #fff;
    border: 1px solid #006896;
    font-size: 14px;
    font-weight: 400;
    color: #006896;
    padding: 0 5px;
    margin: 0 5px;
    .anticon {
      color: #006896;
      margin: 2px 6px 0 0;
    }
    &.active {
      color: #fff;
      background: #006896;
      .anticon {
        color: #fff;
      }
    }
  }
}
.card_list {
  padding: 0 20px 20px;
}
</style>
