<script setup>
import { computed, getCurrentInstance, onMounted, reactive, ref } from "vue";
const { proxy } = getCurrentInstance();
const { D_BZ_XB, D_ZDXL_FGXLRW_YJDJ, D_ZDXL_FGXLRW_RWZT } = proxy.$dict("D_BZ_XB", "D_ZDXL_FGXLRW_YJDJ", "D_ZDXL_FGXLRW_RWZT");
import PageTitle from "@/components/aboutTable/PageTitle.vue";
import Search from "@/components/aboutTable/Search.vue";
import MyTable from "@/components/aboutTable/MyTable.vue";
import Pages from "@/components/aboutTable/Pages.vue";
import EditAddFormDialog from "@/views/backOfficeSystem/service/taskPage/dailyTaskPackage/editAddFormDialog.vue";
import Export from "@/components/export/index.vue";
import { fetchIssueData, selectPagezdy } from "@/api/service/dailyTaskPackage";

const searchConfiger = reactive([
  {
    showType: "input",
    prop: "fgMc",
    placeholder: "请输入方格名称",
    label: "方格名称"
  },{
    showType: "select",
    prop: "fgYjdj",
    placeholder: "请选择预警等级",
    label: "预警等级:",
    options: D_ZDXL_FGXLRW_YJDJ
  },
  {
    showType: "date",
    prop: "rwRq",
    placeholder: "请选择任务日期",
    label: "任务日期:",
  },
])
const searchBox = ref() //搜索框
const deleteIds = ref([]) // 删除id
const isImport = ref(false);
const dialogFormVisible = ref(false);
const pageData = reactive({
  visible: true,
  tableData: [], //表格数据
  keyCount: 0,
  tableConfiger: {
    rowHieght: 61,
    showSelectType:'checkBox',
    loading:false
  },
  total: 0,
  pageConfiger: {
    pageSize: 10,
    pageCurrent: 1
  }, //分页
  controlsWidth: 210, //操作栏宽度
  tableColumn: [
    {
      label: "方格名称 ",
      prop: "fgMc"
    },
    {
      label: "预警等级",
      prop: "fgYjdj",
      showSolt:true
    },
    {
      label: "任务标题",
      prop: "fgRwbt"
    },
    {
      label: "任务日期",
      prop: "rwRq",
    },
    {
      label: "巡逻时长",
      prop: "xlghSc",
      showSolt:true
    },
    {
      label: "盘查人员",
      prop: "xlghPcRy",
    },
    {
      label: "盘查车辆",
      prop: "xlghPcCl",
    },
    {
      label: "巡逻里程",
      prop: "xlghXllc",
      showSolt:true
    },
    {
      label: "下发巡组",
      prop: "xfxz",
    },
    {
      label: "每个打卡点",
      prop: "bddListLabel",
      showOverflowTooltip: true,
    },
    {
      label: "下发状态",
      prop: "rwZt",
      showSolt:true
    },
  ]
})

const selectable = (row) => {
  const targetDate = new Date(row?.rwRq);
  const today = new Date();
  return targetDate.toDateString() === today.toDateString() && (row?.rwZt === '01' || row?.rwZt === '02');
  // return row?.rwZt === "01" || row?.rwZt === "02";
}

const editAddFormRef = ref(null);
const addEdit = (row, type) => {
  editAddFormRef.value?.open(row, type)
}

const handleIssueAll = () => {
  if (deleteIds.value.length === 0) {
    proxy.$message({
      message: "请选择勾选要下发的任务",
      type: "warning"
    });
    return
  }

  handleIssue(deleteIds.value)
}
// 下发
const handleIssue = async (ids = []) => {
  try {
    await proxy.$confirm("是否进行下发操作", "警告", {type: "warning"})

    const res = await fetchIssueData({ ids: ids?.join(',') })

    if (res) {
      proxy.$message({type: "success", message: "下发成功" });
      handleFilter()
      deleteIds.value = []
    }
  } catch (error) {
    console.log(error);
  }
}

// 删除
const delDictItem = (id) => {
  batchDelete(id)
}

const chooseData = (val) => {
  if (val?.length > 0) {
    deleteIds.value = val?.map((item) => item.id);
  } else {
    deleteIds.value = []
  }
}
const onSearch = (val) => {
  const { cz, ...ret } = val
  pageData.pageConfiger.pageCurrent = 1;
  getListData(ret);
}

// 表格高度计算
const tabHeightFn = () => {
  pageData.tableHeight = window.innerHeight - searchBox.value.offsetHeight - 244;
  window.onresize = function () { tabHeightFn(); };
};

const parseAndJoinLx = (jsonString, type = 'lx') => {
  if (!jsonString) return '';

  try {
    let data = jsonString;

    // 如果是字符串，尝试解析为JSON
    if (typeof jsonString === 'string') {
      data = JSON.parse(jsonString);
    }

    // 处理数组情况
    if (Array.isArray(data)) {
      return data.map(item => item?.[type]).filter(Boolean).join(",");
    }

    // 处理对象情况
    if (typeof data === 'object' && data !== null) {
      return data?.[type] || '';
    }

    return '';

  } catch (error) {
    console.warn('数据处理失败:', error);
    return '';
  }
};

const getListData = async (params = {}) => {
  pageData.tableConfiger.loading = true
  try {
    const res = await selectPagezdy({
      ...pageData.pageConfiger,
      ...params
    })
    pageData.tableData = res?.records?.map((item) => ({
      ...item,
      xfxz: item?.xfbb?.fzrXm ? `${item?.xfbb?.fzrXm}警组` : '',
      bddListLabel: item?.bddList?.map((i, idx) => (`卡点${idx + 1}-${i?.xlghDkcs}次`))?.join(',') || '',
      fgJqtjXsLabel: item.fgJqtjXs?JSON.parse(item?.fgJqtjXs)?.filter(i => (i?.count !== 0))?.map(i => (`${i?.hour}小时-${i?.count}起`))?.join('、'): '',
      fgJqtjLx: parseAndJoinLx(item?.fgJqtjLx, 'lx')
    })) || []
    // pageData.tableData[2].rwRq = '2025-09-18'
    // pageData.tableData[0].rwZt = '01'
    pageData.total = res.total;
    pageData.tableConfiger.loading = false;
  } catch (err) {
    pageData.tableConfiger.loading = false;
  }
}

const changeNo = (val) => {
  pageData.pageConfiger.pageCurrent = val;
  getListData();
}

const changeSize = (val) => {
  pageData.pageConfiger.pageSize = val;
  getListData();
}

const handleFilter = (reset = true) => {
  // reset 是否重置 pageCurrent = 1
  if (reset) pageData.pageConfiger.pageCurrent = 1;
  getListData();
}

const isVisibleDel = (row = {}) => {
  const targetDate = new Date(row?.rwRq);
  const today = new Date();
  return targetDate.toDateString() === today.toDateString() && (row?.rwZt === '01' || row?.rwZt === '02');
}

// 删除的方法
//批量删除数据
const batchDelete = async (id) => {
  await proxy.$confirm("确定要删除", "警告", { type: "warning" })

  try {
    // await zbPbDelete(id)

    proxy.$message({
      message: "删除成功",
      type: "success"
    });
    getListData();
  } catch (error) {
    console.log(error);
  }
};

// 批量删除
const handleDel = () => {
  if (deleteIds.value.length === 0) {
    proxy.$message({
      message: "请选择勾选要删除的数据",
      type: "warning"
    });

    return
  }

  batchDelete(deleteIds)
}

onMounted(() => {
  proxy.mittBus.on("mittFn", (data) => { pageData.keyCount = data; });
  tabHeightFn()

  getListData()
})
</script>

<template>
  <div class="container">
    <div class="titleBox">
      <PageTitle title="自定义日常任务包">
        <el-button typeof="danger" :disabled="deleteIds.length === 0" @click="handleIssueAll">
          <span style="vertical-align: middle">批量下发</span>
        </el-button>
        <el-button type="primary" @click="isImport = true">
          <span style="vertical-align: middle">导入</span>
        </el-button>
<!--        <el-button typeof="danger" :disabled="deleteIds.length === 0" @click="handleDel">-->
<!--          <el-icon style="vertical-align: middle"><Delete /> </el-icon>-->
<!--          <span style="vertical-align: middle">批量删除</span>-->
<!--        </el-button>-->
      </PageTitle>
    </div>
    <div ref="searchBox">
      <Search :searchArr="searchConfiger" @submit="onSearch" />
    </div>

    <div class="tabBox">
      <MyTable
        :tableData="pageData.tableData"
        :tableColumn="pageData.tableColumn"
        :tableHeight="pageData.tableHeight"
        :key="pageData.keyCount"
        :tableConfiger="pageData.tableConfiger"
        :controlsWidth="pageData.controlsWidth"
        :selectable="selectable"
        @chooseData="chooseData"
      >
        <template #fgYjdj="{ row }">
          <dict-tag :options="D_ZDXL_FGXLRW_YJDJ" :value="row.fgYjdj" :tag="false" />
        </template>
        <template #rwZt="{ row }">
        <dict-tag :options="D_ZDXL_FGXLRW_RWZT" :value="row.rwZt" :tag="false" />
        </template>
        <template #xlghXllc="{ row }">
          <div>{{ `${row.xlghXllc}公里` }}</div>
        </template>
        <template #xlghSc="{ row }">
          <div>{{ `${row.xlghSc}分钟` }}</div>
        </template>
        <!-- 操作 -->
        <template #controls="{ row }">
          <el-button size="small" v-if="isVisibleDel(row)" @click="addEdit(row, 'del')">编辑</el-button>
          <el-button size="small" @click="addEdit(row, 'view')">查看详情</el-button>
          <el-button size="small" v-if="isVisibleDel(row)" @click="handleIssue([row.id])">下发</el-button>
<!--          <el-button size="small" @click="delDictItem([row.id])">删除</el-button>-->
        </template>
      </MyTable>

      <Pages
        @changeNo="changeNo"
        @changeSize="changeSize"
        :tableHeight="pageData.tableHeight"
        :pageConfiger="{
          ...pageData.pageConfiger,
          total: pageData.total
        }"
      />
    </div>

    <edit-add-form-dialog ref="editAddFormRef" v-model="dialogFormVisible" @ok="handleFilter" />
    <Export
      :show="isImport"
      lx="zdyrcrwb"
      @closeImport="isImport = !isImport"
      @handleImport="handleFilter"
    />
  </div>
</template>

<style scoped lang="scss">
.container {
  ::v-deep {
    .check, .el-upload-text {
      display: none;
    }

    .el-descriptions__body {
      background-color: transparent !important;
      color: #fff;
    }
  }
}

</style>
