<!-- TaskManagement.vue -->
<template>
  <div
    class="L-main"
    id="L-size-main"
  >
    <div
      class="content-search"
      id="L-header"
    >
      <div class="search-title">查询条件</div>
      <el-form
        :inline="true"
        :model="formInline"
        size="medium"
        class="demo-form-inline"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="任务名称：">
              <el-input
                v-model="formInline.taskName"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="任务状态：">
              <el-select
                v-model="formInline.taskStatus"
                placeholder="请选择"
              >
                <el-option
                  label="已关闭"
                  value="0"
                ></el-option>
                <el-option
                  label="进行中"
                  value="1"
                ></el-option>
                <el-option
                  label="正常完成"
                  value="2"
                ></el-option>
                <el-option
                  label="超期完成"
                  value="3"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="任务完成时间：">
              <el-date-picker
                v-model="formInline.time"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="请选择"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col
            :span="6"
            style="text-align: right; padding-left: 20px"
          >
            <el-form-item>
              <el-button @click="resetQuery">重置</el-button>
              <el-button
                type="primary"
                @click="handleQuery"
                >查询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <main>
      <div class="search-title">
        <span class="search-title-span">任务列表</span>
        <el-row
          :gutter="10"
          class="mb8"
        >
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              @click="handleAdd"
              >任务创建</el-button
            >
          </el-col>
        </el-row>
      </div>
      <section>
        <el-table
          v-loading="loading"
          :data="tableData"
          :height="tabHeader"
          :max-height="tabHeader"
          :row-class-name="tableRowClassName"
        >
          <el-table-column
            type="index"
            width="70"
            label="序号"
            align="center"
          />
          <el-table-column
            label="任务名称"
            key="taskName"
            prop="taskName"
            align="center"
          />
          <el-table-column
            label="任务下发时间"
            key="taskTime"
            prop="taskTime"
            align="center"
          />
          <el-table-column
            label="任务期限"
            key="taskDeadline"
            prop="taskDeadline"
            align="center"
          />
          <el-table-column
            label="任务完成时间"
            key="taskFinishTime"
            prop="taskFinishTime"
            align="center"
          />
          <el-table-column
            label="任务状态"
            key="taskStatus"
            width="200px"
            prop="taskStatus"
            class-name="table-status"
            align="center"
          >
            <template #default="scope">
              <span
                v-if="scope.row.taskStatus == 0"
                style="color: #f56c6c"
                >已关闭</span
              >
              <span
                v-if="scope.row.taskStatus == 1"
                style="color: #e6a23c"
                >进行中</span
              >
              <span
                v-if="scope.row.taskStatus == 2"
                style="color: #67c23a"
                >正常完成</span
              >
              <span
                v-if="scope.row.taskStatus == 3"
                style="color: #67c23a"
                >超期完成</span
              >
              <span
                v-if="scope.row.taskStatus == 4"
                style="color: #f56c6c"
                >审核不通过</span
              >
              <span
                v-if="scope.row.taskStatus == 5"
                style="color: #f56c6c"
                >审核驳回</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            prop="userId"
            class-name="table-operation"
            align="center"
          >
            <template #default="scope">
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <div
                  style="display: flex; align-items: center; cursor: pointer"
                  @click="goInfo(scope.row)"
                >
                  <img
                    src="@/assets/images/icon-ck@2x.png"
                    alt=""
                    style="width: 20px; margin-right: 5px"
                  />
                  <span
                    class="look-info"
                    style="color: #1485ef"
                    >查看</span
                  >
                </div>
                <div
                  v-if="scope.row.taskStatus == 1 && scope.row.taskStatus != 0"
                  style="
                    display: flex;
                    align-items: center;
                    cursor: pointer;
                    margin-left: 10px;
                  "
                  @click="delInfo(scope.row)"
                >
                  <img
                    src="@/assets/images/icon-shenhe@2x.png"
                    alt=""
                    style="width: 15px; margin-right: 5px"
                  />
                  <span
                    class="del-info"
                    style="color: #1485ef"
                    >审核</span
                  >
                </div>
                <div
                  v-if="scope.row.taskStatus == 1 && scope.row.taskStatus != 0"
                  style="
                    display: flex;
                    align-items: center;
                    cursor: pointer;
                    margin-left: 10px;
                  "
                  @click="guanbijiekou(scope.row)"
                >
                  <i class="el-icon-delete"></i>
                  <span
                    class="del-info"
                    style="color: #1485ef"
                    >关闭</span
                  >
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </section>
      <my-pagination
        id="L-pagination"
        :total="total"
        :page="pagination.current"
        :limit="pagination.size"
        @pagination="getPagination"
        :current-page.sync="pagination.current"
      >
      </my-pagination>
    </main>

    <my-dialog
      title="新增任务"
      @close="importClose"
      ref="taskDialog"
      class="taskDialogBox"
      width="43%"
    >
      <el-row>
        <el-col :span="21">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleFormRef"
            label-width="120px"
          >
            <el-form-item
              label="任务名称"
              prop="taskName"
            >
              <el-input
                v-model="ruleForm.taskName"
                placeholder="请输入任务名称"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="核查资产类型"
              prop="type"
            >
              <el-checkbox-group
                v-model="ruleForm.type"
                @change="checkboxChange"
              >
                <el-checkbox label="0">web资产</el-checkbox>
                <el-checkbox label="1">小程序资产</el-checkbox>
                <el-checkbox label="2">公众号资产</el-checkbox>
                <el-checkbox label="3">电子邮件资产</el-checkbox>
                <el-checkbox label="4">移动应用程序资产</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
              label="核查单位"
              prop="dwmc"
              class="select-box"
            >
              <el-col>
                <el-select
                  v-model="ruleForm.dwmc"
                  placeholder="请选择核查单位"
                  multiple
                  collapse-tags
                  @remove-tag="isclear"
                >
                </el-select>
              </el-col>
              <el-col class="btn-box">
                <el-button
                  type="primary"
                  @click="addliebiao"
                  ><i class="el-icon-s-unfold"></i
                ></el-button>
              </el-col>
            </el-form-item>
            <el-form-item
              label="任务期限"
              prop="taskDeadline"
            >
              <el-date-picker
                type="datetime"
                placeholder="选择日期"
                v-model="ruleForm.taskDeadline"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
                default-time="23:59:59"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item class="newTask-form-item">
              <el-button @click="resetForm">取消</el-button>
              <el-button
                type="primary"
                @click="submitForm"
                :loading="btnloading"
                >发布</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6"></el-col>
      </el-row>
    </my-dialog>

    <div class="newTask-liebiao">
      <my-dialog
        title="单位列表"
        ref="liebiaoDialog"
        @close="liebiaoClose"
        class="taskDialogBox"
        width="80%"
      >
        <danweiList
          ref="danweiList"
          @adddanweilist="adddanweilist"
          @liebiaoClose="liebiaoClose"
        ></danweiList>
      </my-dialog>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
// import myPagination from "@/views/components/Pagination/index.vue";
// import myDialog from "@/views/components/myDialog/index.vue";
// import danweiList from "@/views/system/user/danweiList.vue";
import {
  addassetTaskadd,
  getassetTask,
  getassetTaskid,
  assetTaskclose,
} from "@/api/renwuApi/index.js";

export default {
  //   components: { myPagination, myDialog, danweiList },
  setup() {
    const router = useRouter();

    // Refs
    const taskDialog = ref(null);
    const liebiaoDialog = ref(null);
    const danweiList = ref(null);
    const ruleFormRef = ref(null);

    // Data
    const pickerOptions = {
      disabledDate(time) {
        const date = new Date();
        const oneday = date.getTime();
        return time.getTime() < new Date().getTime() - 86400000;
      },
      selectableRange: (() => {
        let data = new Date();
        let hour = data.getHours();
        let minute = data.getMinutes();
        let second = data.getSeconds();
        return [`${hour}:${minute}:${second} - 23:59:59`];
      })(),
    };

    const btnloading = ref(false);
    const formInline = ref({
      name: "",
      type: "",
      time: [],
      number: "",
      status: "",
    });
    const total = ref(0);
    const pagination = ref({
      current: 1,
      size: 10,
    });
    const tableData = ref([]);
    const loading = ref(false);
    const tabHeader = ref(undefined);
    const ruleForm = ref({
      taskName: "",
      dwmc: [],
      taskDeadline: "",
      type: [],
    });
    const rules = ref({
      taskName: [{ required: true, message: "请输入", trigger: "change" }],
      dwmc: [{ required: true, message: "请选择", trigger: "change" }],
      taskDeadline: [
        { required: true, message: "请选择日期", trigger: "change" },
      ],
      type: [{ required: true, message: "请选择", trigger: "change" }],
    });
    const tabclicklist = ref([]);

    const chanckList = ref([
      { lable: "0", conent: "web资产" },
      { lable: "1", conent: "小程序资产" },
      { lable: "2", conent: "公众号资产" },
      { lable: "3", conent: "电子邮件资产" },
      { lable: "4", conent: "移动应用程序资产" },
    ]);

    // Methods
    const isclear = (value) => {
      tabclicklist.value = tabclicklist.value.filter(
        (user) => user.nickName != value
      );
    };

    const checkboxChange = () => {
      ruleForm.value.dwmc = [];
      tabclicklist.value = [];
      setTimeout(() => {
        ruleFormRef.value.clearValidate();
      }, 0);
    };

    const resetForm = () => {
      ruleForm.value = {
        dwmc: [],
        taskName: "",
        taskDeadline: "",
        type: [],
      };
      taskDialog.value.close();
      tabclicklist.value = [];
      btnloading.value = false;
    };

    const fonsisis = (data) => {
      const specificTime = new Date(data);
      const currentTime = new Date();
      return currentTime <= specificTime;
    };

    const submitForm = async () => {
      if (!fonsisis(ruleForm.value.taskDeadline)) {
        ElMessage.error("选择时间不能小于当前时间");
        return false;
      }

      try {
        await ruleFormRef.value.validate();
        btnloading.value = true;

        const formData = {
          ...ruleForm.value,
          dwmc: ruleForm.value.dwmc.join(","),
          type: ruleForm.value.type.join(","),
        };

        await addassetTaskadd(formData);
        resetForm();
        getInfo();
        ElMessage.success("新增成功");
      } catch (error) {
        console.log("error submit!!", error);
      } finally {
        btnloading.value = false;
      }
    };

    const adddanweilist = (val) => {
      if (val) {
        ruleForm.value.dwmc = val.map((element) => element.nickName);
      } else {
        ruleForm.value.dwmc = [];
      }
      tabclicklist.value = val || [];
    };

    const getInfo = async () => {
      loading.value = true;
      try {
        const res = await getassetTask(pagination.value);
        total.value = res.data.total;
        tableData.value = res.data.records;
      } finally {
        loading.value = false;
      }
    };

    const resetQuery = () => {
      formInline.value = {
        name: "",
        type: "",
        time: [],
        number: "",
        status: "",
      };
      pagination.value = {
        current: 1,
        size: 10,
      };
      localStorage.removeItem("ismypagination");
      getInfo();
    };

    const addliebiao = () => {
      if (ruleForm.value.type.length > 0) {
        liebiaoDialog.value.open();
        setTimeout(() => {
          danweiList.value.getType(ruleForm.value.type);
          if (tabclicklist.value) {
            setTimeout(() => {
              danweiList.value.dakai(tabclicklist.value);
            }, 100);
          }
        }, 10);
      } else {
        ElMessage("请先选择核查资产类型");
      }
    };

    const liebiaoClose = () => {
      danweiList.value.queryParams = {
        current: 1,
        size: 10,
        userName: undefined,
        nickName: undefined,
        dwlx: undefined,
      };
      liebiaoDialog.value.close();
    };

    const handleQuery = () => {
      pagination.value = {
        current: 1,
        size: 10,
      };

      if (formInline.value.time.length > 0) {
        formInline.value.begainTime = formInline.value.time[0];
        formInline.value.endTime = formInline.value.time[1];
      }

      pagination.value = { ...pagination.value, ...formInline.value };
      formInline.value.isfanhui = false;
      localStorage.setItem("ismypagination", JSON.stringify(formInline.value));
      getInfo();
    };

    const getPagination = (pages) => {
      pagination.value.current = pages.page;
      pagination.value.size = pages.limit;
      getInfo();
    };

    const handleAdd = () => {
      taskDialog.value.open();
      setTimeout(() => {
        ruleFormRef.value.clearValidate();
      }, 100);
    };

    const importClose = () => {
      resetForm();
    };

    const goInfo = (row) => {
      getassetTaskid(row.id);
      router.push({
        name: "TaskInfo",
        query: {
          pageType: "look",
          id: row.id,
        },
      });
    };

    const delInfo = (row) => {
      router.push({
        name: "TaskInfo",
        query: {
          pageType: "info",
          id: row.id,
        },
      });
    };

    const guanbijiekou = (row) => {
      ElMessageBox.confirm("此操作将关闭任务, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await assetTaskclose({ taskId: row.id, taskName: row.taskName });
            ElMessage.success("关闭成功!");
            getInfo();
          } catch (error) {
            console.error(error);
          }
        })
        .catch(() => {
          ElMessage.info("已取消关闭");
        });
    };

    const tableRowClassName = ({ rowIndex }) => {
      return rowIndex % 2 !== 0 ? "evenNumber-row" : "";
    };

    const cancalDebounce = () => {
      const element = document.getElementById("L-size-main");
      const header = document.getElementById("L-header");
      const pagination = document.getElementById("L-pagination");
      const elementHeight = element.offsetHeight;
      const headerHeight = header.offsetHeight;
      const paginationtHeight = pagination.offsetHeight;
      tabHeader.value = elementHeight - headerHeight - paginationtHeight - 110;
    };

    // Lifecycle hooks
    onMounted(() => {
      if (localStorage.getItem("ismypagination")) {
        const storedData = JSON.parse(localStorage.getItem("ismypagination"));
        if (storedData.isfanhui) {
          formInline.value = storedData;
          handleQuery();
        } else {
          localStorage.removeItem("ismypagination");
        }
      }
      localStorage.removeItem("ismypaginationTow");
      localStorage.removeItem("activeName");
      getInfo();
      cancalDebounce();
      window.addEventListener("resize", cancalDebounce);
    });

    onUnmounted(() => {
      window.removeEventListener("resize", cancalDebounce);
    });

    return {
      // Refs
      taskDialog,
      liebiaoDialog,
      danweiList,
      ruleFormRef,

      // Data
      pickerOptions,
      btnloading,
      formInline,
      total,
      pagination,
      tableData,
      loading,
      tabHeader,
      ruleForm,
      rules,
      tabclicklist,
      chanckList,

      // Methods
      isclear,
      checkboxChange,
      resetForm,
      fonsisis,
      submitForm,
      adddanweilist,
      getInfo,
      resetQuery,
      addliebiao,
      liebiaoClose,
      handleQuery,
      getPagination,
      handleAdd,
      importClose,
      goInfo,
      delInfo,
      guanbijiekou,
      tableRowClassName,
      cancalDebounce,
    };
  },
};
</script>

<style lang="scss" scoped>
.el-icon-s-unfold {
  font-size: 16px;
}

// ::v-deep .el-dialog__body{
//   padding-left: 80px;
// }
.el-icon-delete {
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  margin-right: 5px;
}
</style>
