<template>
  <div>
    <van-nav-bar
      title="热线工单"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <template #right>
        <van-icon name="plus" />
      </template>
    </van-nav-bar>
    <div class="body">
      <van-dropdown-menu>
        <van-dropdown-item v-model="value1" :options="option1" />
        <van-dropdown-item v-model="value2" :options="option2" />
      </van-dropdown-menu>

      <div class="listcontent" :style="`height:${bodyheight}px`">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div
              style="padding: 10px 10px; padding-bottom: 0"
              v-for="item in tasklist"
            >
              <div
                @click="gotodetail(item)"
                :class="
                  item.status < 5 &&
                  item.tblTaskLogList.filter((ii) => ii.taskStatus === 6)
                    .length > 0
                    ? 'item warning-row'
                    : 'item'
                "
              >
                <div>
                  <div class="header">
                    <div>工单号:{{ item.taskOtherId }}</div>
                    <div class="time">{{ item.taskTime }}</div>
                  </div>
                  <div class="body">
                    <div class="status">
                      {{
                        task_status.filter(
                          (i) =>
                            i.value.toString() ===
                            (item.status ?? "").toString()
                        )[0]?.label ?? "-"
                      }}
                    </div>

                    <van-row>
                      <van-col span="12"
                        ><div>
                          工单来源:{{
                            task_type.filter(
                              (i) =>
                                i.value.toString() ===
                                (item.taskType ?? "").toString()
                            )[0]?.label ?? "-"
                          }}
                        </div></van-col
                      >
                      <van-col span="12"
                        ><div>
                          事件类型:{{
                            task_event_type.filter(
                              (i) =>
                                i.value.toString() ===
                                (item.taskEventType ?? "").toString()
                            )[0]?.label ?? "-"
                          }}
                        </div></van-col
                      >

                      <van-col :span="12"
                        >接单人：{{
                          allusers
                            .filter(
                              (i) =>
                                [item.taskReporter + ""].indexOf(
                                  i.userId + ""
                                ) != -1
                            )
                            .map((i) => i.nickName)
                            .join(",")
                        }}</van-col
                      >
                      <!-- <van-col span="12">
                        <div>接单人:{{ item.taskReporter }}</div></van-col
                      > -->
                      <van-col span="12"
                        ><div>
                          联系方式:{{ item.taskComplainConnect }}
                        </div></van-col
                      >
                      <van-col span="24"
                        ><div>任务内容: {{ item.taskContent }}</div></van-col
                      >
                      <van-col span="24">
                        <div>地址: {{ item.taskAddr }}</div>
                      </van-col>
                    </van-row>
                    <van-row
                      v-if="
                        item.status == 2 &&
                        (item.tblTaskLogList ?? []).filter(
                          (i) => i.taskStatus == -1
                        ).length < 1
                      "
                    >
                      <van-col span="24">
                        <div style="text-align: right">
                          <van-button
                            type="primary"
                            size="small"
                            @click.stop="receivetask(item)"
                            >接收任务</van-button
                          >
                        </div>
                      </van-col>
                    </van-row>

                    <van-row
                      v-if="
                        item.status == 2 &&
                        (gettaskitemlogdes(item, -1) ?? {}).zyfzr ===
                          getters.userId
                      "
                    >
                      <van-col span="24">
                        <div style="text-align: right">
                          <van-button
                            v-if="
                              (gettaskitemlogdes(item, -1) ?? {}).ddxctime ===
                              ''
                            "
                            type="primary"
                            size="small"
                            @click.stop="daoda(item)"
                            style="margin-right: 10px"
                            >到达现场</van-button
                          >
                          <van-button
                            v-if="
                              (gettaskitemlogdes(item, -1) ?? {}).ddxctime !==
                              ''
                            "
                            type="primary"
                            size="small"
                            @click.stop="bhfk(item)"
                            style="margin-right: 10px"
                            >驳回反馈</van-button
                          >
                          <van-button
                            v-if="item.status === 2"
                            type="primary"
                            size="small"
                            @click.stop="czfk(item)"
                            >处置反馈</van-button
                          >

                          <van-button
                            type="primary"
                            size="small"
                            :disabled="
                              (gettaskitemlogdes(item, -2) ?? { status: 1 })
                                .status !== 1
                            "
                            style="margin-left: 10px"
                            @click.stop="ysclick(item)"
                            >{{
                              (gettaskitemlogdes(item, -2) ?? { status: 1 })
                                .status === 1
                                ? "申请延期"
                                : (gettaskitemlogdes(item, -2) ?? { status: 1 })
                                    .status === 0
                                ? "申请中"
                                : "已拒绝"
                            }}</van-button
                          >
                        </div>
                      </van-col>
                    </van-row>
                  </div>
                </div>
              </div>
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
    <van-action-sheet v-model:show="showys" title="延时申请">
      <div style="padding: 15px; text-align: center; padding-bottom: 30px">
        <van-field name="slider" label="时间">
          <template #input>
            <van-slider
              v-model="yqnum"
              @change="onyqnumChange"
              :min="1"
              :max="50"
            >
              <template #button>
                <div class="custom-sbutton">{{ yqnum }}</div>
              </template>
            </van-slider>
          </template>
          <template #button>
            <span>小时</span>
          </template>
        </van-field>
        <van-field
          v-model="yqcontent"
          rows="1"
          autosize
          label="说明"
          type="textarea"
          placeholder="请输入理由"
        />
        <van-button
          type="primary"
          style="width: 90%; margin: auto"
          @click="doyssq"
          >申请</van-button
        >
      </div>
    </van-action-sheet>
  </div>
</template>

<script setup>
import { defineComponent, ref, onMounted, watch, computed } from "vue";
import { useDict } from "@/utils/dict";
import router from "../../../router";
import {
  listTask,
  getTask,
  delTask,
  addTask,
  updateTask,
  ddTask,
} from "@/api/system/task";
import { Toast } from "vant";
import moment from "moment";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
} from "@/api/system/user";

const tasklist = ref([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);

const { task_status, task_event_category, task_event_type, task_type } =
  useDict("task_status", "task_event_category", "task_event_type", "task_type");

const bodyheight = ref(0);
bodyheight.value = document.body.clientHeight - 48 - 46;
const value1 = ref(0);
const yqnum = ref(0);
const yqcontent = ref("");
const value2 = ref("0");
const option1 = [
  { text: "我的", value: 0 },
  { text: "全部", value: 1 },
];
const option2 = computed(() => {
  return [{ text: "全部", value: "0" }].concat(
    task_status.value.map((i) => {
      return { text: i.label, value: i.value };
    })
  );
});

const onyqnumChange = (value) => {
  // Toast(value);
};

const gotodetail = (item) => {
  router.push(`/mb/task/detail/${item.taskId}`);
};
const store = useStore();
const getters = computed(() => store.getters);

const pagec = ref(1);

const onLoad = () => {
  if (refreshing.value) {
    tasklist.value = [];
    refreshing.value = false;
    pagec.value = 1;
  }
  var p = { pageSize: 10, pageNum: pagec.value++ };
  if (value2.value !== "0") {
    p["status"] = parseInt(value2.value);
  }
  if (value1.value == "0") {
    p["params"] = {};
    p.params["userId"] = getters.value.userId;
  }
  listTask(p).then((res) => {
    // finished.value = true;
    loading.value = false;
    tasklist.value = tasklist.value.concat(res.rows);
    if (res.total <= tasklist.value.length) {
      finished.value = true;
    }
  });
};

watch(
  () => value2.value,
  () => {
    refreshing.value = true;
    onLoad();
  }
);
watch(
  () => value1.value,
  () => {
    refreshing.value = true;
    onLoad();
  }
);

const onRefresh = () => {
  // 清空列表数据
  finished.value = false;
  loading.value = true;
  refreshing.value = true;
  onLoad();
};

const onClickLeft = () => {
  router.back();
};
const onClickRight = () => {
  router.push("/mb/task/add");
};

const showys = ref(false);

const xyobj = ref({
  bzxytime: "",
  ddxctime: "",
  czwctime: "",
  zysc: "",
  clsc: "",
  zyfzr: "",
  zyrs: 0,
  carxh: "",
  carnumber: "",
  gls: "",
});

const allusers = ref([]);
listUser({ pageSize: 1000 }).then((res) => {
  allusers.value = res.rows;
});

const gettaskitemlogdes = (item, status) => {
  var templist = {};
  var list = item.tblTaskLogList;
  for (var i in list) {
    var log = list[i];
    if (templist.hasOwnProperty(log.taskStatus + "")) {
      if (
        moment(templist[log.taskStatus + ""].createTime).unix() -
          moment(log.createTime).unix() <
        0
      ) {
        templist[log.taskStatus + ""] = log;
      }
    } else {
      templist[log.taskStatus + ""] = log;
    }
  }
  var lists = [];
  for (var i in templist) {
    lists.push(templist[i]);
  }
  if (
    templist[status + ""] == null ||
    templist[status + ""] == undefined ||
    templist[status + ""] == ""
  )
    return null;
  return JSON.parse(templist[status + ""].logDes);
};

const receivetask = (item) => {
  var logc = gettaskitemlogdes(item, -1);
  if (logc != null) {
    xyobj.value = logc;
  }

  xyobj.value.bzxytime = moment().format("YYYY-MM-DD HH:mm:ss");
  xyobj.value.zyfzr = getters.value.userId;
  console.log(xyobj.value);
  ddTask({
    taskId: item.taskId,
    taskStatus: -1,
    logDes: JSON.stringify(xyobj.value),
  }).then((res) => {
    Toast.success("成功");
    onRefresh();
  });
};

const daoda = (item) => {
  var logc = gettaskitemlogdes(item, -1);
  if (logc != null) {
    xyobj.value = logc;
  }
  xyobj.value.ddxctime = moment().format("YYYY-MM-DD HH:mm:ss");
  xyobj.value.zyfzr = getters.value.userId;

  ddTask({
    taskId: item.taskId,
    taskStatus: -1,
    logDes: JSON.stringify(xyobj.value),
  }).then((res) => {
    Toast.success("成功");
    onRefresh();
  });
};
const czfk = (item) => {
  localStorage.setItem("currenttask", JSON.stringify(item));
  router.push(`/mb/task/disposal?id=${item.taskId}`);
};

const bhfk = (item) => {
  localStorage.setItem("currenttask", JSON.stringify(item));
  router.push(`/mb/task/disposal?bh=1&id=${item.taskId}`);
};

var currentitem = null;
const ysclick = (item) => {
  showys.value = true;
  currentitem = item;
};

const doyssq = () => {
  if (currentitem == null) {
    Toast("未知错误");
    showys.value = false;
    return;
  }
  ddTask({
    taskId: currentitem.taskId,
    taskStatus: -2,
    logDes: JSON.stringify({
      yqsc: yqnum.value,
      yqcontent: yqcontent.value,
      status: 0, //0申请 1 同意 2拒绝
    }),
  }).then((res) => {
    Toast.success("成功");
    onRefresh();
  });
  showys.value = false;
};
</script>

<style lang="scss">
body {
  position: fixed;
  width: 100%;
  top: -1px;
}
.custom-sbutton {
  width: 26px;
  color: #fff;
  font-size: 10px;
  line-height: 18px;
  text-align: center;
  background-color: var(--van-button-primary-background-color);
  border-radius: 100px;
}
.warning-row {
  background: var(--el-color-warning-light-9) !important;
}

.listcontent {
  overflow-y: auto;

  .item {
    background: #fff;
    border: 1px solid rgba(209, 217, 221, 0.4);
    padding: 10px 15px;
    font-size: 10px;
    border-radius: 5px;
    .header {
      color: #3d6dc5;
      font-weight: bold;
      position: relative;
      padding-bottom: 8px;
      border-bottom: 1px solid rgba(209, 217, 221, 0.4);
      .time {
        position: absolute;
        right: 0;
        top: 0;
        color: #283247;
        opacity: 0.7;
        font-weight: 400;
      }
    }
    .body {
      padding-top: 10px;
      padding-bottom: 10px;
      position: relative;
      color: #283247;
      opacity: 0.8;
      .status {
        position: absolute;
        top: 10px;
        color: #dc2828;
        right: 0px;
        font-weight: bold;
      }
      .van-col {
        margin: 3px 0;
      }
    }
  }
}
</style>
