<template>
  <!-- 设备初始化审批 -->
  <div class="taskMessagePage flex-col">
    <s-header :name="$t('taskMessage.taskMessage')" :noback="false"></s-header>
    <div class="taskMessageBox flex-col">
      <van-list v-model:loading="loading" v-model:error="error" :error-text="$t('common.reqFailClkReload')"
        :finished="finished" :finished-text="$t('common.noMoreTxt')" offset="300" :immediate-check="false" @load="onLoad">
        <div class="searchRow flex-row justify-between">
          <div class="flex-col">
            <div class="flex-row justify-between bd3">
              <div class="flex-col outer4 equipmentIcon"></div>
              <span class="flex-col txt2">{{ $t("taskMessage.total")
              }}<span class="discountNumber">{{ alarmHistoryTotal }}</span>{{ $t("taskMessage.recordsInTotal") }}</span>
            </div>
          </div>
          <div class="l-flex-RC">
            <div @click="reviewedClk" class="label3 o-mr-30">
              {{ $t("taskMessage.toViewAppro") }}
            </div>
            <div @click="noticeClk" class="main5 l-flex-RC">
              <img class="label2 o-mr-5" src="../../../assets/device/searchIcon.png" />
              <span class="txt3">{{ $t("taskMessage.search") }}</span>
            </div>
          </div>
        </div>
        <div class="listBox">
          <div v-for="(item, index) in alarmHistoryList" :key="index" class="listItem">
            <div class="itemBox">
              <div class="itemRow">
                <span class="itemTitle">{{ $t("taskMessage.affiliatedMerchants") }}:&nbsp;</span>{{ item.adminUserName }}
              </div>
              <div class="itemRow">
                <span class="itemTitle">{{ $t("taskMessage.equipmentNo") }}:&nbsp;</span>{{ item.clientId }}
              </div>
              <div class="itemRow">
                <span class="itemTitle">{{ $t("taskMessage.managementSystemID") }}:&nbsp;</span>{{ item.managerId }}
              </div>
              <div class="itemRow" v-if="item.statusType === 1">
                <span class="itemTitle">{{ $t("taskMessage.state") }}:&nbsp;</span><span style="color: red">{{
                  showItemType(item.statusType)
                }}</span>
              </div>
              <div class="itemRow">
                <span class="itemTitle">{{ $t("taskMessage.applicationTime") }}:&nbsp;</span>{{
                  showDateTime(item.createDate) }}
              </div>
              <div class="itemRow" v-if="item.statusType !== 1">
                <span class="itemTitle">{{ $t("taskMessage.approvalTime") }}:&nbsp;</span>{{ showDateTime(item.modifyDate)
                }}
              </div>
              <div v-if="item.statusType === 1 && isOper" class="itemRow"
                style="display: flex; justify-content: flex-end">
                <van-button span="5" round type="primary" style="
                      height: 2em;
                      padding: 0 2em;
                      margin: 0 1em;
                      background: rgb(255 0 0 / 20%);
                      color: #ff0000;
                      border-color: #ff0000;
                    " @click="changeStatusFun(item, 'unAgreed')">
                  {{ $t("taskMessage.refuse") }}
                </van-button>
                <van-button span="5" round type="primary" style="
                      height: 2em;
                      padding: 0 2em;
                      margin: 0 1em;
                      background: rgb(25 137 250 / 20%);
                      color: #1989fa;
                    " @click="changeStatusFun(item, 'agreed')">
                  {{ $t("taskMessage.agree") }}
                </van-button>
              </div>
              <div class="itemRow" style="display: flex; justify-content: flex-end">
                <span v-if="item.statusType === 2" style="color: #ff0000">{{
                  showItemType(item.statusType)
                }}</span>
                <span v-if="item.statusType === 3" style="color: #4fc08d">{{
                  showItemType(item.statusType)
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </div>
    <!-- 筛选弹窗 -->
    <kDialog :dialogTitle="$t('taskMessage.equipmentInit.searchPop.title')"
      :confirmBtnTxt="$t('taskMessage.equipmentInit.searchPop.filterBtn')" ref="kDialogRef" @confirmclk="confirmClk">
      <template #content>
        <div class="cust_vantBorder">
          <van-field clearable v-model="searchForm.equipmentNo" :placeholder="$t('taskMessage.equipmentInit.searchPop.equipmentNoPlace')
            " :label="$t('taskMessage.equipmentInit.searchPop.equipmentNo')" />
          <van-field clearable v-model="searchForm.managementSystemID" :placeholder="$t('taskMessage.equipmentInit.searchPop.managementSystemIDPlace')
            " :label="$t('taskMessage.equipmentInit.searchPop.managementSystemID')
    " />
          <van-field clearable v-model="searchForm.merchantName" :placeholder="$t('taskMessage.equipmentInit.searchPop.merchantNamePlace')
            " :label="$t('taskMessage.equipmentInit.searchPop.merchantName')" />
          <van-field @click-input="busiInpClk" readonly clearable v-model="searchForm.stateName"
            :placeholder="$t('taskMessage.equipmentInit.searchPop.statePlace')"
            :label="$t('taskMessage.equipmentInit.searchPop.state')">
            <template #right-icon>
              <div class="l-flex-RC">
                <van-icon v-if="searchForm.stateName" @click="
                  searchForm.stateName = '';
                searchForm.state = '';
                " class="o-mr-6" name="clear" />
                <van-icon @click="busiInpClk" name="arrow-down" />
              </div>
            </template>
          </van-field>
        </div>
      </template>
    </kDialog>
    <!-- 状态选择框 -->
    <van-popup v-model:show="busiPopShow" position="bottom">
      <van-picker :title="$t('taskMessage.equipmentInit.searchPop.statePlace')" :columns="busiPopList"
        :columns-field-names="busiPopFieldName" @confirm="busiPopConfirm" @cancel="busiPopShow = false" />
    </van-popup>
  </div>
</template>

<script>
import { onMounted, reactive, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import { getTaskEquipmentList, changeStatus } from "@/service/taskMessage";
import { showSuccessToast, showFailToast } from "vant";
import { getLoginUser, styleUrl } from "@/common/js/utils";
import dateUtil from "@/utils/dateUtil";
import kDialog from "@/components/commom/kDialog/index.vue";
import { useI18n } from "vue-i18n";
import { useRouter } from 'vue-router'

export default {
  components: { sHeader, kDialog },
  setup() {
    const { t } = useI18n();
    const router = useRouter()
    // 筛选弹窗
    const busiPopList = reactive([
      {
        name: t("taskMessage.toBeApproved"),
        id: "1",
      },
      {
        name: t("taskMessage.rejected"),
        id: "2",
      },
      {
        name: t("taskMessage.agreed"),
        id: "3",
      },
    ]);
    const busiPopFieldName = reactive({
      text: "name",
      value: "id",
    });
    const kDialogRef = ref(null);
    const busiPopShow = ref(false);
    // 筛选条件
    const searchForm = reactive({
      equipmentNo: "",
      managementSystemID: "",
      merchantName: "",
      state: "",
      stateName: "",
    });
    // 点击状态输入框
    const busiInpClk = () => {
      busiPopShow.value = true;
    };
    const busiPopConfirm = ({ selectedOptions }) => {
      busiPopShow.value = false;
      searchForm.state = selectedOptions[0].id;
      searchForm.stateName = selectedOptions[0].name;
    };
    // 点击筛选
    const noticeClk = () => {
      kDialogRef.value.openDialog();
    };
    // 点击查询按钮
    const confirmClk = () => {
      isClkReview.value = false;
      searchGetList();
    };
    // 是否点击待审核
    const isClkReview = ref(true);
    // 点击查看待审核
    const reviewedClk = () => {
      isClkReview.value = true;
      searchParams.statusType = "1";
      // 清空弹窗的查询条件
      searchForm.state = "";
      searchForm.stateName = "";
      searchGetList();
    };
    const user = getLoginUser();
    const loading = ref(false); // 加载状态
    const error = ref(false); // 错误状态
    const finished = ref(false); // 结束翻页状态
    const alarmHistoryList = ref([]); // 列表集合
    const alarmHistoryTotal = ref(0); // 列表总数
    let searchParams = reactive({
      clientId: "", // 设备编号_支持模糊查询
      current: 1, // 页数
      size: 20, // 页大小
      userName: "", // 用户登录名
      statusType: "", // 审核状态 1 - 申请中 2 - 已拒绝 3 - 已同意
      managerId: "", // 管理系统ID
    });
    // 滚动加载
    const onLoad = () => {
      if (!finished.value) {
        searchParams.current = searchParams.current + 1;
        getList();
      }
    };
    // 查询列表
    const searchGetList = () => {
      alarmHistoryList.value = [];
      searchParams.current = 1;
      getList();
    };
    // 获取设备初始化审批列表数据
    const getList = async () => {
      // 把弹窗的筛选条件组合到请求参数里面
      if (!isClkReview.value) {
        searchParams.statusType = searchForm.state;
      }
      searchParams.clientId = searchForm.equipmentNo;
      searchParams.userName = searchForm.merchantName;
      searchParams.managerId = searchForm.managementSystemID;
      const { data } = await getTaskEquipmentList(
        Object.assign({}, searchParams)
      );
      if (data.code === "00000") {
        // 列表值叠加
        alarmHistoryList.value = alarmHistoryList.value.concat(
          data.data.records
        );
        alarmHistoryTotal.value = data.data.total;
        if (alarmHistoryList.value.length === data.data.total) {
          finished.value = true;
        }
        loading.value = false;
      } else {
        showFailToast(data.message);
      }
    };
    const showDateTime = (date) => {
      return date
        ? dateUtil.formateDate(new Date(date), "yyyy-MM-dd hh:mm:ss")
        : "";
    };
    const showItemType = (type) => {
      if (type === 1) {
        return t("taskMessage.toBeApproved");
      }
      if (type === 2) {
        return t("taskMessage.rejected");
      }
      if (type === 3) {
        return t("taskMessage.agreed");
      }
      return "";
    };
    const changeStatusFun = async (item, status) => {
      try {
        const res = await changeStatus({ id: item.id, status: status });
        showSuccessToast({
          message: res.data.message,
          forbidClick: true,
          duration: 1500,
        });
        setTimeout(() => {
          router.go(0); // 刷新当前页面
        }, 1500); // 延迟1.5秒后执行刷新操作
      } catch (error) {
        console.error(error);
        // 处理错误情况
      }
      // changeStatus({ id: item.id, status: status }).then((res) => {
      //   getList();
      // });
    };
    // 是否有操作的权限
    const isOper = ref(true);
    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      styleUrl('taskMessage');
      if (user) {
        searchParams.adminId = user.id;
        searchGetList();
        // 如果是type大于1，那么不能有操作的权限
        if (user.type > 1) {
          isOper.value = false;
        }
      }
    });
    return {
      loading,
      error,
      finished,
      onLoad,
      alarmHistoryList,
      alarmHistoryTotal,
      showDateTime,
      showItemType,
      changeStatusFun,
      kDialogRef,
      noticeClk,
      confirmClk,
      busiInpClk,
      busiPopConfirm,
      busiPopShow,
      searchForm,
      busiPopList,
      busiPopFieldName,
      reviewedClk,
      isOper,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../../common/style/common.less";
</style>
  