<template>
  <z-paging
    class="page inspection"
    ref="paging"
    v-model="dataList"
    @query="queryList"
  >
    <!-- z-paging默认铺满全屏，此时页面所有view都应放在z-paging标签内，否则会被盖住 -->
    <!-- 需要固定在页面顶部的view请通过slot="top"插入，包括自定义的导航栏 -->
    <template #top>
      <view class="page-top">
        <view class="page-back"></view>
        <view class="uni-page-head navgator justify-center align-center">
          <view class="nav-back" @click="navigatorBack()">
            <uni-icons type="left"></uni-icons>
          </view>
          <view class="nav-title">
            {{ $t("inspection.title") }}
          </view>
        </view>
        <view class="page-content">
          <view class="content-search">
            <uni-easyinput
              prefixIcon="search"
              confirmType="search"
              v-model="search"
              :placeholder="$t('common.searchHint')"
              @confirm="onSearch"
            >
            </uni-easyinput>
          </view>
          <uni-row
            class="content-statistics flex-row align-center justify-around"
          >
            <uni-col class="statistics-item flex-col align-center">
              <view class="statistics-count font-BiaoTiHei">
                {{ statistics.total }}
              </view>
              <view class="statistics-title">
                {{ $t("inspection.totalWorkOrders") }}
              </view>
            </uni-col>
            <uni-col class="statistics-item flex-col align-center">
              <view class="statistics-count font-BiaoTiHei">
                {{ statistics.finished }}
              </view>
              <view class="statistics-title">
                {{ $t("workOrder.executed") }}
              </view>
            </uni-col>
            <uni-col class="statistics-item flex-col align-center">
              <view class="statistics-count font-BiaoTiHei">
                {{ statistics.todo }}
              </view>
              <view class="statistics-title">
                {{ $t("workOrder.pending") }}
              </view>
            </uni-col>
          </uni-row>
        </view>
      </view>
    </template>
    <view class="paging-list">
      <view class="item" v-for="(item, index) in dataList" :key="index">
        <view
          class="item-module flex-row align-center justify-between"
          :class="{ tobeFilled: item.result == 1 ,ignore: item.status == 'ignore'}"
        >
          <!-- 工单编号 -->
          <view class="module-name">
            {{ $t("workOrder.workOrderNumber") }}: {{ item.inspectOrderCode }}
          </view>
          <view
            class="module-status"
            :class="{ finished: item.status == 'finished',ignore: item.status == 'ignore'}"
          >
            <span>{{ statusDict[item.status] ? statusDict[item.status] : "" }}</span>
          </view>
        </view>
        <view class="item-content">
          <!-- 工单名称 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("workOrder.workOrderName") }}:</span
            >
            <span>{{ item.inspectOrderTitle }}</span>
          </view>
          <view class="item-title flex-row">
            <!-- 工单状态(1待执行 2已执行) -->
            <span class="item-title-width">{{ $t("workOrder.workOrderStatus") }}:</span>
            <span>{{ statusDict[item.status] ? statusDict[item.status] : "" }}</span>
          </view>
          <view class="item-title flex-row">
            <!-- 工单类型(1计划生成 2临时新建) -->
            <span class="item-title-width"
              >{{ $t("workOrder.workOrdertype") }}:</span
            >
            <span>{{ item.type }}</span>
          </view>
          <!-- 负责人 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("workOrder.responsiblePerson") }}:</span
            >
            <span>{{ item.chargeName }}</span>
          </view>
          <!-- 应检设备数 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("inspection.equipmentNum") }}:</span
            >
            <span>{{ item.deviceCount }}</span>
          </view>
          <!-- 漏检设备数 -->
          <view class="item-title flex-row">
            <span class="item-title-width">{{ $t("inspection.misNum") }}:</span>
            <span class="color-green">{{ item.needDevice }}</span>
          </view>
          <!-- 异常设备数 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("inspection.abnormalNum") }}:</span
            >
            <span class="color-red">{{ item.exceptionCount }}</span>
          </view>

          <!-- 创建时间 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("operation.createTime") }}:</span
            >
            <span>{{
              item.createTime ? formatDate(item.createTime) : ""
            }}</span>
          </view>
          <!-- 执行时间 -->
          <view class="item-title flex-row">
            <span class="item-title-width">
              {{ $t("workOrder.executionTime") }}:
            </span>
            <span>
              {{ item.executeDate ? formatDate(item.executeDate) : "" }}
            </span>
          </view>
        </view>
        <view class="item-btn flex-row align-center justify-end">
          <button type="primary" :plain="true" @click="navigatorDetail(item)">
            {{ $t("workOrder.viewDetails") }}
          </button>
          <button
            type="primary"
            class="btn-ignore"
            :plain="false"
            v-if="item.status == 'todo'"
            @click="handleIgnore(item)"
          >
            {{ $t("operation.ignore") }}
          </button>
          <button
            type="primary"
            :plain="false"
            v-if="item.status == 'todo'"
            @click="navigatorEdit(item)"
          >
            {{ $t("operation.fill") }}
          </button>
        </view>
      </view>
    </view>
  </z-paging>
  <!-- 忽略输入弹窗 -->
  <uni-popup
    class="ignore-unipopup"
    ref="ignorePopupRef"
    type="bottom"
    :animation="false"
    :mask-click="false"
    borderRadius="10px 10px 10px 10px"
  >
    <view class="ignore-popup-box">
      <view>
        <uni-row class="flex-row align-center">
          <uni-col class="ignore-popup-title" :span="22">
            {{ $t("operation.ignoreReason") }}
          </uni-col>
          <uni-col :span="2">
            <uni-icons
              type="closeempty"
              size="20"
              color="#999"
              @click="closeIgnorePopup"
            ></uni-icons>
          </uni-col>
        </uni-row>
      </view>
      <view class="ignore-popup-content">
        <uni-easyinput
          type="textarea"
          class="ignore-popup-textarea"
          :placeholder="
            $t('operation.PleaseFillIn') + $t('operation.ignoreReason')
          "
          v-model="ignoreReason"
        ></uni-easyinput>
      </view>
      <view class="ignore-popup-btn">
        <button type="primary" @click="confirmIgnore">
          {{ $t("operation.submit") }}
        </button>
      </view>
    </view>
  </uni-popup>
</template>
<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick, warn } from "vue";
import { onShow } from "@dcloudio/uni-app";

import {
  getInspectCount,
  getInspectOrderList,
  inspectOrderIgnore,
} from "@/api/inspection";

import dayjs from "dayjs";
import { useDataDictStore } from "@/store/modules/dataDict";
// 引用全局变量$t
const { appContext } = getCurrentInstance();
const t = appContext.config.globalProperties.$t;
const { getDataDictList } = useDataDictStore();
// 状态
const statusDict = reactive({});
getDataDictList("pms_inspect_order_status").map((item) => {
  statusDict[item.value] = item.label;
});
console.log("statusDict", statusDict);
// 审核状态
const auditStatusDict = reactive({});
getDataDictList("crm_audit_status").map((item) => {
  auditStatusDict[item.value] = item.label;
});
console.log("auditStatusDict", auditStatusDict);
//  --- 列表 ---start---
const search = ref("");
const paging = ref(null);
// v-model绑定的这个变量不要在分页请求结束中自己赋值，直接使用即可
const dataList = ref([]);

// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用paging.value.reload()即可
const queryList = (pageNo, pageSize) => {
  // 此处请求仅为演示，请替换为自己项目中的请求
  getInspectOrderList({
    pageNo,
    pageSize,
    commonParam: search.value,
  })
    .then((res) => {
      // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
      paging.value.complete(res.data.list);
    })
    .catch((res) => {
      // 如果请求失败写paging.value.complete(false);
      // 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
      // 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
      paging.value.complete(false);
    });
};
const onSearch = () => {
  paging.value.reload();
};
const formatDate = (time) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};
// -- end --
//  获取顶部统计数量
const statistics = reactive({});
const getCount = async () => {
  getInspectCount().then((res) => {
    const { data } = res;

    statistics.total = data?.total || 0;
    statistics.todo = data?.todo || 0;
    statistics.finished = statistics.total - statistics.todo;
  });
};
// 忽略弹窗
const ignorePopupRef = ref(null);
// 忽略巡检项
const ignoreItem = ref(null);
// 忽略理由
const ignoreReason = ref("");
const handleIgnore = (item) => {
  ignoreItem.value = item;
  ignorePopupRef.value.open();
};
const closeIgnorePopup = () => {
  ignorePopupRef.value.close();
  ignoreReason.value = "";
};
// 忽略弹窗确认
const confirmIgnore = (e) => {
  console.log("🚀 ~ confirmIgnore ~ e:", e);
  if (!ignoreReason.value) {
    uni.showToast({
      title: t("operation.PleaseFillIn") + t("operation.ignoreReason"),
      icon: "none",
    });
    return;
  }
  // 调用接口忽略巡检项
  inspectOrderIgnore({
    id: ignoreItem.value.id,
    reason: ignoreReason.value,
  })
    .then((res) => {
      console.log("🚀 ~ confirmIgnore ~ res:", res)
      if (res.code == 0) {
        uni.showToast({
          title: t("operation.success"),
          icon: "success",
        });
        closeIgnorePopup();
        nextTick(() => {
          getCount();
          onSearch();
        });
      }
    })
    .catch((res) => {
      uni.showToast({
        title: res.message || t("operation.failed"),
        icon: "none",
      });
    });
};

const navigatorDetail = (item) => {
  uni.navigateTo({
    url: "/pages/inspection/detail?id=" + item.id,
  });
};
const navigatorEdit = (item) => {
  uni.navigateTo({
    url: "/pages/inspection/edit?id=" + item.id,
  });
};
const navigatorBack = () => {
  uni.navigateBack();
};
onShow(() => {
  console.log("inspection - onShow");
  getCount();
  nextTick(() => {
    onSearch();
  });
});
</script>
<style lang="scss" scoped>
@import "@/style/work-order.scss";
.btn-ignore {
  margin-left: 10px;
  background-color: #e6a23c !important;
  border-color: #e6a23c !important;
  color: #fff;
}
.ignore-popup-box {
  padding: 20px;
  background: #fff;
  border-radius: 10px 10px 0 0;
}
.ignore-popup-title {
  text-align: center;
}
.ignore-popup-close {
  text-align: right;
}
.ignore-popup-content {
  margin: 15px;
}
</style>
