<template>
  <div class="my-alert">
    <div class="breadcrumb">
      <bg-breadcrumb />
    </div>
    <div class="content">
      <bg-filter-group @search="changeSearch" v-model="filter.search" placeholder="请输入任务名称">
        <template v-slot:left_action>
          <div class="apaas_button">
            <el-button type="primary" @click="AddTicket">
              <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-add"></bg-icon>
              新增
            </el-button>
            <el-button type="primary" @click="delBatch"> 批量删除 </el-button>
            <div class="select_text">
              <span>已选择</span>
              <span class="num">{{ selectedItems.length }}</span>
              <span>项</span>
              <span class="can_click_text" @click="clearSelected">清空</span>
            </div>
          </div>
        </template>
        <template v-slot:filter_group>
          <div class="left-filter filter_list">
            <div class="filter_item">
              <span class="filter_title">工单等级</span>
              <el-select v-model="filter.order_level" placeholder="请选择" style="width: 300px">
                <el-option
                  v-for="(item, index) in ticketLevelOptions"
                  :key="'order_level_options' + index"
                  :label="item"
                  :value="index">
                </el-option>
              </el-select>
            </div>
            <div class="filter_item">
              <span class="filter_title">状态</span>
              <el-select v-model="filter.order_state" placeholder="请选择" style="width: 300px">
                <el-option
                  v-for="(item, index) in statusOptions"
                  :key="'order_state_options' + index"
                  :label="item"
                  :value="index">
                </el-option>
              </el-select>
            </div>
            <div class="filter_item">
              <span class="filter_title">定时规则</span>
              <el-select v-model="filter.timing_type" placeholder="请选择" style="width: 300px">
                <el-option
                  v-for="(item, index) in ruleOptions"
                  :key="'ruleOptions' + index"
                  :label="item"
                  :value="index">
                </el-option>
              </el-select>
            </div>
            <div class="filter_item">
              <span class="filter_title">创建时间</span>
              <el-date-picker
                v-model="filter.create_time"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间">
              </el-date-picker>
            </div>
          </div>
          <div class="right-action apaas_button">
            <el-button type="primary" @click="filterAction"> 查询 </el-button>
            <el-button type="default" @click="filterClear"> 重置 </el-button>
          </div>
        </template>
      </bg-filter-group>
      <div class="table_container">
        <div class="table">
          <bg-table
            ref="listtable"
            :headers="headers"
            :rows="rows"
            height="100%"
            :isIndex="true"
            :select="true"
            @selectAc="selectRows"
            :selectable="selectable"
            :stripe="true">
            <template #order_name="{ row }">
              <div class="href" @click="goTo(row)">{{ row.order_name || "-" }}</div>
            </template>
            <template #order_state="{ row }">
              <span>{{ ticketLevelOptions[row.order_level] }}</span>
            </template>
            <template #timing_type="{ row }">
              <span>{{ ruleOptions[row.timing_type] }}</span>
            </template>
            <template #create_time="{ row }">
              {{ dateStringToDate(row.create_time) }}
            </template>
            <template #timing_state="{ row }">
              <el-switch
                v-model="row.timing_state"
                active-text="是"
                inactive-text="否"
                inline-prompt
                :active-value="true"
                :inactive-value="false"
                @change="Enable(row)">
              </el-switch>
            </template>
            <template #operation="{ row }">
              <div class="table-operation">
                <el-button type="primary" link size="default" @click="operation(row)">手动下发</el-button>
                <span class="line"></span>
                <el-button type="primary" link size="default" @click="Edit(row)" :disabled="row.timing_state">
                  编辑
                </el-button>
                <span class="line"></span>
                <el-button type="primary" link size="default" @click="Delete(row)" :disabled="row.timing_state">
                  删除
                </el-button>
              </div>
            </template>
          </bg-table>
          <div class="pagination_box">
            <bg-pagination
              :page="filter.page"
              :size="filter.page_size"
              :total="tableTotal"
              @change-page="changePage"
              @change-size="changeSize">
            </bg-pagination>
          </div>
        </div>
      </div>
      <ManualDistribution v-model:visible="visible" :row="active_row" :is_all="true" />
    </div>
    <!-- 删除 -->
    <el-dialog class="dialog_box" title="删除" v-model="delDialog" width="420px">
      <div>确定要删除吗？</div>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="delDialog = false">取消</el-button>
          <el-button type="primary" @click="delConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import ManualDistribution from "@/components/manual-distribution/index.vue";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
import { useRouter } from "vue-router";
import { dateStringToDate } from "@/components/env";
const router = useRouter();
const filter = reactive({
  order_level: "",
  search: "",
  create_time: [],
  timing_type: [],
  order_state: "",
  page: 1,
  page_size: 10,
});
const filterClear = () => {
  filter.order_level = "";
  filter.search = "";
  filter.order_state = "";
  filter.create_time = [];
  filter.timing_type = [];
  filter.page_size = 10;
  filter.page = 1;
  changePage(1);
}; // 重置筛选项
const tableTotal = ref(0);
const ticketLevelOptions = ["全部", "紧急任务", "重要任务", "一般任务"];
const statusOptions = ["全部", "待处置", "已完成", "已关闭"];
const ruleOptions = ["全部", "手动下发", "按周", "自定义时间"];
let headers = reactive([
  {
    label: "工单名称",
    prop: "order_name",
    align: "left",
  },
  {
    label: "工单等级",
    prop: "order_level",
    align: "left",
  },
  {
    label: "实例工单数",
    prop: "order_cnt",
    align: "left",
  },
  {
    label: "下发对象",
    prop: "push_obj",
    align: "left",
  },
  {
    label: "定时规则",
    prop: "timing_type",
    align: "left",
  },
  {
    label: "定时是否启用",
    prop: "timing_state",
    align: "left",
    width: 150,
  },
  {
    label: "创建人",
    prop: "create_user",
    align: "left",
  },
  {
    label: "创建时间",
    prop: "create_time",
    align: "left",
    width: 160,
  },
  {
    label: "操作",
    prop: "operation",
    align: "left",
    width: "220px",
    fixed: "right",
  },
]);
let rows = ref([]);
const selectable = (row, index) => {
  return !row.timing_state;
};
const changeSize = (size) => {
  filter.page_size = size;
  changePage(1);
};

const changePage = (page) => {
  filter.page = page;
  getTableRows();
};
const changeSearch = (val) => {
  filter.search = val;
  changePage(1);
}; // 表格关键字筛选

const filterAction = () => {
  changePage(1);
}; // 查询按钮

const getTableRows = async () => {
  let [create_date_from = "", create_date_to = ""] = filter.create_time || [];
  let urlParams = {
    ...filter,
    create_date_from,
    create_date_to,
  };
  Reflect.deleteProperty(urlParams, "create_time");
  axios.get("/v1/api/work_order/work_order_manage/list", { params: urlParams }).then((res) => {
    if (res.data.code == 200) {
      rows.value =
        res.data.data?.map((e) => {
          return { ...e, timing_state: e.timing_state == 1 };
        }) || [];
      tableTotal.value = res.data.total;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
// 手动下发
const visible = ref(false);
const active_row = ref(null);
const operation = (row) => {
  active_row.value = row;
  visible.value = true;
};
// 编辑调用
const Edit = (row) => {
  active_row.value = row;
  router.push({
    path: "/ticket/business-ticket-manage/edit",
    query: {
      id: row.id,
    },
  });
};
// 删除调用
const selectedItems = ref([]);
const Delete = (row) => {
  selectedItems.value = [row];
  delBatch();
};
const del_ids = computed(() => {
  return selectedItems.value.map((e) => e.id) || [];
});
// 表格选中
const selectRows = ({ selection }) => {
  selectedItems.value = selection;
};
// 新增
const AddTicket = () => {
  router.push({
    path: "/ticket/business-ticket-manage/add",
  });
};
const delDialog = ref(false);
// 批量删除
const delBatch = () => {
  if (del_ids.value.length == 0) {
    ElMessage({
      message: "请选择要删除的工单",
      type: "error",
      duration: 3000,
    });
    return;
  }
  delDialog.value = true;
};
// 删除确定
const delConfirm = () => {
  const params = {
    id: del_ids.value,
  };
  axios
    .delete("/v1/api/work_order/work_order_manage/del", {
      data: params,
    })
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("删除成功！");
        clearSelected();
        delDialog.value = false;
        changePage(1);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};
// 清空选中
const listtable = ref(null);
const clearSelected = () => {
  listtable.value.clearTable();
};
const goTo = ({ id }) => {
  router.push({
    path: "/ticket/business-ticket-manage/detail",
    query: {
      id,
    },
  });
};
const Enable = (row) => {
  const params = {
    id: row.id,
    timing_state: row.timing_state ? 1 : 0,
  };
  axios.put("/v1/api/work_order/work_order_manage/state", params).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("定时是否启用修改成功");
      changePage(1);
    } else {
      ElMessage.error(res.data.msg);
      row.timing_state = !row.timing_state;
    }
  });
};
onMounted(() => {
  getTableRows();
});
</script>

<style lang="scss" scoped>
.my-alert {
  width: 100%;
  height: 100%;
  padding: 0 24px 16px;
  .breadcrumb {
    width: 100%;
    height: 46px;
  }
  .content {
    width: 100%;
    height: calc(100% - 46px);
    background-color: #ffffff;
    box-shadow: 0px 1px 4px 0px rgba(0, 7, 101, 0.15);
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    padding: 16px;
    :deep(.bg-filter-group) {
      padding: 0;
    }
    .select_text {
      display: inline-block;
      margin-left: 40px;
      font-size: 14px;
      color: #404a62;
      .num {
        color: #202531;
        font-weight: 700;
        margin: 0 3px;
      }
      .can_click_text {
        margin-left: 24px;
        cursor: pointer;
      }
    }
    .filter-group {
      .left-filter {
        display: flex;
        justify-content: start;
        flex-wrap: wrap;
      }
      .right-action {
        white-space: nowrap;
      }
    }
    .table_container {
      flex: 1;
      display: flex;
      flex-direction: column;
      position: relative;
      .table {
        position: absolute;
        flex: 1;
        width: 100%;
        height: calc(100% - 48px);
        .href {
          font-size: 14px;
          color: #3759be;
          cursor: pointer;
        }
      }
    }
    .bg-pagination {
      bottom: unset;
    }
    .table-operation {
      display: flex;
      align-items: center;
      .line {
        width: 1px;
        height: 14px;
        background-color: #c1c7d7;
        margin: 0 16px;
        display: inline-block;
      }
    }
    :deep(.el-button.is-link) {
      line-height: 1;
    }
    :deep(.el-switch) {
      height: 20px;
      .el-switch__inner .is-hide {
        display: none;
      }
    }
  }
}
</style>
