<template>
  <z-paging class="page" ref="paging" v-model="dataList" @query="queryList">
    <!-- z-paging默认铺满全屏，此时页面所有view都应放在z-paging标签内，否则会被盖住 -->
    <!-- 需要固定在页面顶部的view请通过slot="top"插入，包括自定义的导航栏 -->
    <template #top>
      <uni-row class="search-row flex-row align-center justify-between">
        <uni-col :span="19">
          <uni-easyinput
            v-model="orderName"
            :styles="inputStyles"
            :placeholderStyle="placeholderStyle"
            :placeholder="$t('operation.searchText')"
          >
          </uni-easyinput>
        </uni-col>
        <uni-col :span="5" class="flex-row justify-end">
          <button
            class="mini-btn"
            type="primary"
            size="mini"
            @click="searchList"
          >
            {{ $t("operation.search") }}
          </button>
        </uni-col>
      </uni-row>
    </template>
    <view class="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.orderStatus == 0,
            ignore: item.orderStatus == 3,
          }"
        >
          <!-- 创建时间 -->
          <view class="module-name">
            {{ item.createTime ? formatDate(item.createTime) : "" }}
          </view>
          <!-- 工单状态 -->
          <view
            class="module-status"
            :class="{
              pending: item.orderStatus == 0,
              ignore: item.orderStatus == 3,
            }"
          >
            {{ fillStatusDict[item.orderStatus] }}
          </view>
        </view>
        <view class="item-content">
          <!-- 负责人 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("operationRecordFilling.responsiblePerson") }}:</span
            >
            <span>{{ item.userName }}</span>
          </view>
          <!-- 工单名称 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("operationRecordFilling.workOrderName") }}:</span
            >
            <span>{{ item.orderName }}</span>
          </view>
          <!-- 工单设备 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("operationRecordFilling.workOrderDevice") }}:</span
            >
            <span>{{ item.fillList }}</span>
          </view>
          <!-- 应填设备数 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("operationRecordFilling.totalDeviceCount") }}:</span
            >
            <span>{{ item.allDev }}</span>
          </view>
          <!-- 已填设备数 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("operationRecordFilling.filledDeviceCount") }}:</span
            >
            <span class="color-green">{{ item.fillDev }}</span>
          </view>
          <!-- 未填设备数 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("operationRecordFilling.unfilledDeviceCount") }}:</span
            >
            <span class="color-red">{{ item.unFillDev }}</span>
          </view>
          <!-- 创建时间 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("operation.createTime") }}:</span
            >
            <span>{{
              item.createTime ? formatTime(item.createTime) : ""
            }}</span>
          </view>
          <!-- 填写时间 -->
          <view class="item-title flex-row">
            <span class="item-title-width"
              >{{ $t("operation.fillTime") }}:</span
            >
            <span>{{
              item.updateTime ? formatTime(item.updateTime) : ""
            }}</span>
          </view>
          <!-- 忽略理由 （仅忽略状态下显示）-->
          <view class="item-title flex-row" v-if="item.orderStatus == 3">
            <span class="item-title-width"
              >{{ $t("operation.ignoreReason") }}:</span
            >
            <span>{{ item.reason }}</span>
          </view>
        </view>
        <view class="item-btn flex-row align-center justify-end">
          <!--  状态：0(待填写),1(已完成),2(填写中),3(忽略) -->
          <!-- 忽略 -->
          <button
            type="default"
            class="btn-ignore"
            v-if="item.orderStatus == 0 || item.orderStatus == 2"
            @click="ignoreOrder(item)"
          >
            {{ $t("operation.ignore") }}
          </button>
          <!-- 查看 -->
          <button
            type="primary"
            plain="true"
            v-if="item.orderStatus == 1 || item.orderStatus == 3"
            @click="navigatorDetail(item, 0)"
          >
            {{ $t("operation.view") }}
          </button>
          <!-- 填写 -->
          <button
            type="primary"
            v-if="item.orderStatus == 0 || item.orderStatus == 2"
            @click="navigatorDetail(item, 1)"
          >
            {{ $t("operation.fill") }}
          </button>
        </view>
      </view>
    </view>
  </z-paging>
  <ignore-reason ref="ignorePopupRef" @ignore-submit="ignoreSubmit" />
</template>

<script setup>
import { ref, reactive, nextTick } from "vue";
import { onShow } from "@dcloudio/uni-app";
import dayjs from "dayjs";
import {
  getRecordFillingList,
  recordFillingIgnore,
} from "@/api/recordFilling.js";
import { getUserId, getDeptId } from "@/utils/auth.js";
import { useDataDictStore } from "@/store/modules/dataDict";
import ignoreReason from "@/components/ignore/reason.vue";

// 获取字典项
const { getStrDictOptions } = useDataDictStore();
// 填写状态
const fillStatusDict = reactive({});
getStrDictOptions("operation_fill_order_status").map((item) => {
  fillStatusDict[item.value] = item.label;
});
console.log("🚀 ~ getDataDictList ~ fillStatusDict:", fillStatusDict);

const orderName = ref("");
const placeholderStyle = ref("color:#797979;font-weight:500;font-size:16px");
const inputStyles = reactive({
  backgroundColor: "#FFFFFF",
  color: "#797979",
});
const paging = ref(null);
// v-model绑定的这个变量不要在分页请求结束中自己赋值，直接使用即可
const dataList = ref([]);

// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用paging.value.reload()即可
const queryList = (pageNo, pageSize) => {
  // 此处请求仅为演示，请替换为自己项目中的请求
  getRecordFillingList({
    pageNo,
    pageSize,
    deptId: getDeptId(),
    orderName: orderName.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 searchList = () => {
  paging.value.reload();
};
const navigatorDetail = (item, type) => {
  console.log("item", item);
  const param = {
    ...item,
    orderId: item.id,
  };

  uni.navigateTo({
    url:
      "/pages/recordFilling/detail?view=" +
      type +
      "&param=" +
      JSON.stringify(param),
  });
};
const formatDate = (time) => {
  return dayjs(time).format("YYYY-MM-DD");
};
const formatTime = (time) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};
const ignoreItem = ref(null);
const ignorePopupRef = ref(null);
const ignoreOrder = (item) => {
  console.log("🚀 ~ ignoreOrder ~ item:", item);
  ignoreItem.value = item;
  ignorePopupRef.value.openIgnore();
};
const ignoreSubmit = (reason) => {
  console.log("🚀 ~ ignoreSubmit ~ reason:", reason);
  recordFillingIgnore({
    id: ignoreItem.value.id,
    reason,
  })
    .then((res) => {
      console.log("🚀 ~ ignoreSubmit ~ res:", res);
      if (res.code !== 0) {
        uni.showToast({
          title: res.msg,
          icon: "error",
        });
        return;
      }
      uni.showToast({
        title: t("operation.success"),
        icon: "success",
      });
      ignorePopupRef.value.close();
      searchList();
    })
    .catch((err) => {
      console.log("🚀 ~ ignoreSubmit ~ err:", err);
      uni.showToast({
        title: err.msg,
        icon: "error",
      });
    });
};

onShow(() => {
  nextTick(() => {
    searchList();
  });
});
</script>

<style lang="scss" scoped>
@import "@/style/work-order.scss";

.search-row {
  height: 35px;
  background: #f3f5f9;

  .mini-btn {
    height: 35px;
    line-height: 35px;
    width: 100%;
    margin-left: 8px;
  }
}

.item {
  width: 100%;
  // height: 245px;
  min-height: 245px;
  // max-height: fit-content;
  background: #ffffff;
  border-radius: 6px;
  margin-top: 10px;
}
</style>
