<template>
  <z-paging
    class="page fault"
    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("home.faultReporting") }}
          </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.faultTotal }}
              </view>
              <view class="statistics-title">
                {{ $t("fault.faultTotal") }}
              </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("status.processed") }}
              </view>
            </uni-col>
            <uni-col class="statistics-item flex-col align-center">
              <view class="statistics-count font-BiaoTiHei">
                {{ statistics.average }}
              </view>
              <view class="statistics-title">
                {{ $t("equipmentMaintenance.averageResolutionTime") }}
              </view>
            </uni-col>
          </uni-row>
          <button class="full-btn" type="primary" @click="onCreate">
            <uni-icons type="plusempty"></uni-icons>
            {{ $t("fault.createButton") }}
          </button>
        </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.status == 'close',
            finished: item.status == 'finished',
          }"
        >
          <view class="module-name">
            {{ $t("fault.faultCode") }}: {{ item.failureCode }}
          </view>
          <view
            class="module-status"
            :class="{
              pending: item.status == 'close',
              finished: item.status == 'finished',
              turn: item.status == 'trans',
            }"
          >
            <!-- 状态 -->
            <span>{{ statusDict[item.status] }}</span>
          </view>
        </view>
        <view class="item-content">
          <!-- 故障名称 -->
          <view class="item-title flex-row">
            <span class="item-title-width">{{ $t("fault.faultName") }}:</span>
            <span>{{ item.failureName }}</span>
          </view>
          <!-- 设备编号 -->
          <view class="item-title flex-row">
            <span class="item-title-width">{{ $t("device.deviceCode") }}:</span>
            <span>{{ item.deviceCode }}</span>
          </view>
          <!-- 设备名称 -->
          <view class="item-title flex-row">
            <span class="item-title-width">{{ $t("device.deviceName") }}:</span>
            <span>{{ item.deviceName }}</span>
          </view>
          <!-- 故障时间 -->
          <view class="item-title flex-row">
            <span class="item-title-width">{{ $t("fault.faultTime") }}:</span>
            <span>{{
              item.failureTime ? formatDate(item.failureTime) : ""
            }}</span>
          </view>
          <!-- 审核状态 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("workOrder.auditStatus") }}:</span
            >
            <span>{{ auditStatusDict[item.auditStatus] }}</span>
          </view>
          <!-- 是否解决 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("workOrder.isSolved") }}:</span
            >
            <span>{{
              item.ifDeal ? $t("operation.yes") : $t("operation.no")
            }}</span>
          </view>
          <!-- 需要协助 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("workOrder.Needassistance") }}:</span
            >
            <span>{{
              item.needHelp ? $t("operation.yes") : $t("operation.no")
            }}</span>
          </view>
          <!-- 工单来源 -->
          <!-- <view class="item-title flex-row">
						<span class="item-title-width">{{$t('workOrder.workOrderSource')}}:</span>
						<span>{{item.maintainType}}</span>
					</view> -->
        </view>
        <view class="item-btn flex-row align-center justify-end">
          <!-- 查看详情 -->
          <button type="primary" :plain="false" @click="navigatorDetail(item)">
            {{ $t("workOrder.viewDetails") }}
          </button>
          <button
            type="primary"
            @click="navigatorEdit(item)"
            v-if="item.status == 'close'"
          >
            {{ $t("operation.edit") }}
          </button>
          <button
            type="default"
            style="color: #e7000d; background-color: #ffebeb"
            @click="onDelete(item)"
            v-if="item.status == 'close'"
          >
            {{ $t("operation.delete") }}
          </button>
        </view>
      </view>
    </view>
  </z-paging>
</template>
<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { getRepairCount } from "@/api/repair";
import { getFaultList, deleteFault, getFaultCount } from "@/api/fault";
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_failure_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) => {
  // 此处请求仅为演示，请替换为自己项目中的请求
  getFaultList({
    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 () => {
  await getFaultCount().then((res) => {
    statistics.faultTotal = res.data?.failureTotal || 0;
  });
  await getRepairCount().then((res) => {
    const { failureStatus } = res.data;
    console.log("failureStatus", failureStatus);
    statistics.finished =  failureStatus?.finished || 0;
    statistics.average = 1.2;
  });
};

const navigatorDetail = (item) => {
  uni.navigateTo({
    url: "/pages/fault/detail?id=" + item.id,
  });
};
const navigatorEdit = (item) => {
  uni.navigateTo({
    url: "/pages/fault/edit?id=" + item.id,
  });
};
const onCreate = () => {
  uni.navigateTo({
    url: "/pages/fault/create",
  });
};
const onDelete = (item) => {
  uni.showModal({
    title: t("api.message"),
    content: t("operation.deleteConfirm"),
    success: function (res) {
      if (res.confirm) {
        console.log("用户点击确定");
        deleteFault({
          id: item.id,
        }).then((res) => {
          uni.showToast({
            title: t("operation.success"),
            icon: "none",
          });
          paging.value.reload();
        });
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};
const navigatorBack = () => {
  uni.navigateBack();
};
onShow(() => {
  getCount();
  nextTick(() => {
    onSearch();
  });
});
</script>
<style lang="scss" scoped>
@import "@/style/work-order.scss";
</style>
