<template>
  <div style="padding: 10px">
    <div class="formbody">
      <el-form
        :inline="true"
        v-model="queryparameters"
        class="demo-form-inline"
      >
        <el-row>
          <el-col :span="4">
            <el-form-item label="工单号">
              <el-input
                v-model="queryparameters.taskCode"
                placeholder="请输入工单号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="任务时间">
              <el-date-picker
                v-model="qdate"
                type="daterange"
                value-format="YYYY-MM-DD"
                range-separator="到"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3" v-if="currentstatus == 1">
            <el-form-item label="任务状态">
              <el-select
                v-model="queryparameters.status"
                class="m-1"
                placeholder="请选择"
              >
                <el-option label="全部" value="0"></el-option>
                <el-option
                  v-for="item in task_status"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="事件来源">
              <el-select
                v-model="queryparameters.taskType"
                class="m-2"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in task_type"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="区属">
              <el-select
                v-model="queryparameters.taskArea"
                class="m-2"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in sys_area"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="班组区域">
              <el-tree-select
                v-model="queryparameters.taskDeptRange"
                multiple
                :data="treedept"
                check-strictly="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="关键字">
              <el-input
                v-model="queryparameters.searchkey"
                placeholder="道路名/任务内容/地址"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="4"> -->
            <div style="float: right">

              <el-form-item>
                <el-button type="primary" @click="getList">查询</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="reset()">重置</el-button>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                    @click.stop="exportexcel3()"
                    >导出
                  </el-button>
             </el-form-item>
              <el-form-item v-if="route.params.status == 6">
                <el-button type="primary" @click="exportexcel2(queryparameters)"
                  >导出成本记录
                </el-button>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="success"
                  @click="addtask"
                  v-if="route.params.status == 1"
                  >新增工单</el-button
                >
              </el-form-item>
            </div>
          <!-- </el-col> -->
        </el-row>
      </el-form>

      <div>
        <el-table
          :data="tableData"
          class="eltable"
          style="width: 100%"
          @row-click="tblrowclick"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="taskOtherId" label="工单号" width="180" />
          <el-table-column prop="taskArea" label="行政区">
            <template #default="scope">
              {{
                (sys_area ?? []).filter(
                  (i) => i.value === scope.row.taskArea + ""
                )[0]?.label ?? "-"
              }}
            </template>
          </el-table-column>
          <el-table-column label="事件来源">
            <template #default="scope">
              {{
                task_type.filter((i) => i.value === scope.row.taskType + "")[0]
                  ?.label ?? "-"
              }}
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              {{
                task_status.filter((i) => i.value === scope.row.status + "")[0]
                  ?.label ?? "-"
              }}
            </template>
          </el-table-column>
          <el-table-column prop="taskAddrRoad" label="道路名" />
          <el-table-column prop="taskContent" label="任务内容" />
          <el-table-column prop="createTime" label="来件时间" />
          <el-table-column
            prop="taskTime"
            label="剩余时间(办理时限)"
            v-if="currentstatus != 6"
          >
            <template #default="scope"
              ><div>
                <div
                  v-if="scope.row.taskTime != null && scope.row.status < 5"
                  :class="
                    moment(scope.row.taskTime).diff(moment(), 'days') < 2
                      ? 'tip-e'
                      : moment(scope.row.taskTime).diff(moment(), 'days') < 3
                      ? 'tip-w'
                      : moment(scope.row.taskTime).diff(moment(), 'days') > 5
                      ? 'tip-i'
                      : ''
                  "
                >
                  <el-icon style="vertical-align: middle"><Clock /></el-icon>
                  <span>
                    {{
                      moment(scope.row.taskTime).diff(moment(), "days")
                    }}天</span
                  >
                </div>
                <div v-if="scope.row.taskTime == null">-</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="操作"
            :width="currentstatus == 6 ? '400px' : ''"
          >
            <template #default="scope">
              <el-button
                text
                type="primary"
                size="small"
                v-if="route.params.status != 6"
                @click.stop="edittask(scope.row)"
                >修改
              </el-button>
              <el-popconfirm
                title="确定删除?"
                @confirm="deltask(scope.row)"
                v-if="route.params.status == 1"
              >
                <template #reference>
                  <el-button text type="danger" size="small" @click.stop="">删除</el-button>
                </template>
              </el-popconfirm>
              <el-button
                v-if="scope.row.status == 6 && route.params.status == 6"
                text
                type="success"
                size="small"
                @click.stop="exportexcel(scope.row)"
                >导出工单
              </el-button>
              <el-button
                v-if="scope.row.status == 6 && route.params.status == 6"
                text
                type="success"
                size="small"
                @click.stop="exportexcel1(scope.row)"
                >导出热线照片
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="position: relative; padding-right: 20px; margin-top: -20px">
          <Pagination
            :total="pagedata.total ?? 0"
            v-show="pagedata.total > 0"
            v-model:page="queryparameters.pageNum"
            v-model:limit="queryparameters.pageSize"
            @pagination="getList"
          ></Pagination>
          <!-- <el-pagination
          style="float: right"
          small
          background
          :page-sizes="[10, 20, 30, 50]"

          :page-size="10"
          layout=" sizes,prev, pager, next"
          :total="pagedata.total??0"
          class="mt-4"
        /> -->
        </div>
      </div>
    </div>

    <el-dialog
      v-model="showadd"
      v-loading="loading"
      :title="`${
        taskinfo.taskId == null || taskinfo.taskId == undefined
          ? '新增任务'
          : '编辑任务'
      }`"
      width="70%"
      draggable
    >
      <div>
        <TaskAdd v-model:taskinfo="taskinfo" ref="taskaddref"></TaskAdd>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showadd = false">取消</el-button>
          <el-button type="primary" @click="ontaskadd">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineComponent, ref, reactive, onMounted, computed } from "vue";
import { useDict } from "@/utils/dict";
import TaskAdd from "@/components/Task/Add";
import MapSelect from "@/components/MapSelect";
import router from "../../../router";
import { ElMessage } from "element-plus";
// 分页组件
import Pagination from "@/components/Pagination";
import {
  listTask,
  getTask,
  delTask,
  addTask,
  updateTask,
} from "@/api/system/task";
import { cloneDeep } from "lodash";
import { isArray } from "@vue/shared";
import { onBeforeRouteLeave, useRoute } from "vue-router";
import moment from "moment";
import { treeselect as deptTreeselect } from "@/api/system/dept";

const formlocation = ref({ addr: "", locations: "" });

const {
  task_status,
  task_type,
  task_event_type,
  task_event_category,
  sys_area,
} = useDict(
  "task_status",
  "task_type",
  "task_event_type",
  "task_event_category",
  "sys_area"
);
const queryparameters = ref({
  status: "0",
  taskCode: "",
  taskArea: "",
  taskType: "",
  taskDeptRange: [],
  searchkey: "",
  pageNum: 1,
  pageSize: 10,
});
const loading = ref(false);
const { proxy } = getCurrentInstance();
const showadd = ref(false);
const qdate = ref([]);
const tableData = ref([]);
const pagedata = ref({});
const taskinfo = ref({
  taskName: null,
  taskContent: null,
  taskAddr: null,
  taskLocation: null,
  taskCode: null,
  taskType: null,
  taskEventType: null,
  taskEventCategory: null,
  taskFromRemark: null,
  taskAddrRoad: null,
  taskOtherId: null,
  taskTime: null,
  taskArea: "1",
  taskReqCompleteTime: null,
  status: 1,
  taskId: null,
  remark: "",
  taskCreater: null,
  taskReporter: null,
  taskPics: null,
  taskVideos: null,
  taskComplainConnect: null,
  taskDeptRange: "",
  taskFacilitieCode: "",
});
const taskaddref = ref();
const route = useRoute();
const currentstatus = computed(() => route.params.status);

const reset = () => {
  queryparameters.value = {
    status: "0",
    taskCode: "",
    taskArea: "",
    taskType: "",
    taskDeptRange: [],
    searchkey: "",
    pageNum: 1,
    pageSize: 10,
  };
  localStorage.setItem("tasklist", JSON.stringify(queryparameters.value));
  getList()
};

const addtask = () => {
  showadd.value = true;
  taskinfo.value = {
    taskName: null,
    taskContent: null,
    taskAddr: null,
    taskLocation: null,
    taskCode: null,
    taskType: null,
    taskEventType: null,
    taskEventCategory: null,
    taskFromRemark: null,
    taskAddrRoad: null,
    taskOtherId: null,
    taskTime: null,
    taskArea: "1",
    taskReqCompleteTime: null,
    status: 1,
    taskId: null,
    remark: "",
    taskCreater: null,
    taskReporter: null,
    taskPics: null,
    taskVideos: null,
    taskComplainConnect: null,
    taskDeptRange: "",
    taskFacilitieCode: "",
  };
  taskaddref.value?.doinit(taskinfo.value);
};

const tblrowclick = (row) => {
  router.push(`/task/detail/${row.taskId}`);
};
const ontaskadd = async () => {
  taskaddref.value?.updateallvalue();
  showadd.value = false;
  var taskobj = cloneDeep(taskinfo.value);
  taskobj.status = 1;
  taskobj.taskDeptRange =
    taskobj.taskDeptRange instanceof Array
      ? taskobj.taskDeptRange.join(",")
      : "";
  taskobj.taskReqCompleteTime = taskobj.taskReqCompleteTime==null
    ? ""
    : moment(taskobj.taskReqCompleteTime).format("YYYY-MM-DD HH:mm:ss");

  console.log(taskobj);
  loading.value = true;

  if (taskobj.taskId) {
    await updateTask(taskobj).then((res) => {
      ElMessage.success("保存成功");
    });
  } else {
    await addTask(taskobj).then((res) => {
      ElMessage.success("保存成功");
    });
  }

  loading.value = false;
  getList();
};

const getList = () => {
  localStorage.setItem("tasklist", JSON.stringify(queryparameters.value));

  if (
    currentstatus.value !== "1" &&
    currentstatus.value !== 1 &&
    (queryparameters.value.status === "" || queryparameters.value.status==0)
  ) {

    if (currentstatus.value == "2" || currentstatus.value == 2) {
      queryparameters.value.status = 1;
    } else {
      queryparameters.value.status = currentstatus.value;
    }
  } else {
    // queryparameters.value.status = "";
  }
  var cq = cloneDeep(queryparameters.value);

  var query = proxy.addDateRange(cq, qdate.value);
  if (query.status == "0") {
    delete query.status;
  }
  if (query.searchkey != undefined && query.searchkey !== "") {
    query.params["searchkey"] = query.searchkey;
  }
  if (query.taskDeptRange != undefined) {
    query.taskDeptRange = query.taskDeptRange.join(",");
  }

  listTask(query).then((response) => {
    tableData.value = response.rows;
    pagedata.value = response;
  });
};
if (localStorage.getItem("tasklist")!=null) {
  queryparameters.value = JSON.parse(localStorage.getItem("tasklist"));
}

getList();
const edittask = (row) => {
  taskinfo.value = cloneDeep(row);
  showadd.value = true;
  taskaddref.value?.doinit(taskinfo.value);
};
const deltask = (row) => {
  delTask(row.taskId).then((res) => {
    ElMessage.success("删除成功");
    getList();
  });
};
const exportexcel = (row) => {
  proxy.download(
    "system/task/export",
    {
      ...{ taskId: row.taskId },
    },
    `${row.taskCode}工单.xlsx`
  );
};
const exportexcel1 = (row) => {
  proxy.download(
    "system/task/export1",
    {
      ...{ taskId: row.taskId },
    },
    `${row.taskCode}热线照片.xlsx`
  );
};
const exportexcel2 = (row) => {
  proxy.download(
    "system/task/export2",
    {
      ...row,
    },
    `成本记录.xlsx`
  );
};
const exportexcel3 = () => {
  if (
    currentstatus.value !== "1" &&
    currentstatus.value !== 1 &&
    (queryparameters.value.status === "" || queryparameters.value.status == 0)
  ) {

    if (currentstatus.value == "2" || currentstatus.value == 2) {
      queryparameters.value.status = 1;
    } else {
      queryparameters.value.status = currentstatus.value;
    }
  } else {
    // queryparameters.value.status = "";
  }
  var cq = cloneDeep(queryparameters.value);

  var query = proxy.addDateRange(cq, qdate.value);
  if (query.status == "0") {
    delete query.status;
  }
  if (query.searchkey != undefined && query.searchkey !== "") {
    query.params["searchkey"] = query.searchkey;
  }
  if (query.taskDeptRange != undefined) {
    query.taskDeptRange = query.taskDeptRange.join(",");
  }
  proxy.download(
    "system/task/export3",
    {
      ...query,
    },
    `【热线调度】计划、跟进、成果上报.xlsx`
  );
};

const tableRowClassName = ({ row, rowIndex }) => {
  if (
    row.status < 5 &&
    row.tblTaskLogList.filter((ii) => ii.taskStatus === 6).length > 0
  ) {
    return "warning-row";
  }
  return "";
};

function setdatakey(dept) {
  if (dept.children) {
    dept.children = dept.children.map((i) => {
      return setdatakey(i);
    });
  }
  dept["value"] = dept.id;
  return dept;
}

const treedept = ref([
  {
    value: "1",
    label: "ss",
  },
  {
    value: "2",
    label: "ss1",
  },
]);
deptTreeselect().then((res) => {
  treedept.value = [setdatakey(res.data[0].children.filter(i=>i.id==202))[0]];
});

onMounted(() => {
  if (currentstatus.value == "2") {
    queryparameters.value.status = 1;
  } else {
    queryparameters.value.status =
      currentstatus.value == "1" ? "0" : currentstatus.value;
  }
});
onBeforeRouteLeave((to, from, next) => {
  to.meta.activeMenu = from.path;
  console.log(to);
  next()
})


</script>

<style lang="scss" scoped>
.formbody {
  background: #fff;
  width: 100%;
  border-radius: 5px;
  min-height: 80vh;
  padding: 15px 10px;
  .eltable {
    border: 1px solid #e5e9f2;
    border-radius: 5px;
    .tip-e {
      color: red;
    }
    .tip-w {
      color: yellow;
    }
    .tip-i {
      color: green;
    }
  }
}
</style>

<style>
.el-table__row:hover {
  cursor: pointer;
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
</style>
