<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="计划名称" prop="planName" v-if="!visibleSelect" >
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物资柜" prop="cabinetId">
        <el-select
          v-model="queryParams.cabinetId"
          placeholder="请选择检查的物资柜"
          clearable
          :disabled="visibleSelect"
          class="!w-240px"
        >
          <el-option
            v-for="dict in cabinets"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划日期" prop="createTime">
        <el-date-picker
          v-model="createTime"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          @change="handleClearTime(createTime)"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="检察员" prop="checkUserName">
        <el-select
          v-model="queryParams.checkUserName"
          placeholder="请选择检察员"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in planPersonOption"
            :key="dict.value"
            :label="dict.label"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" class="!w-240px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CHECKING_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['iscs:plan:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 自动配置检查计划 -->
  <ContentWrap>
    <el-form label-width="70px">
      <el-row :gutter="10">
        <el-col :span="2" style="margin-top: 8px">
          <el-checkbox
            v-model="autoConfig.startStatus"
            @change="handleClickStatus"
            style="transform: scale(1.5)"
          />
          <span style="margin-left: 6%">启动自动创建</span>
        </el-col >
        <el-col :span="4" style="margin-top: 8px">
          <el-form-item label="计划频率">
            <el-select
              v-model="autoConfig.planFrequency"
              :disabled="!autoConfig.startStatus"
              placeholder="请选择计划频率"
              clearable
              @change="handleFrequencyChange"
              class="!w-240px"
            >
              <el-option label="月" value="月" />
              <el-option label="周" value="周" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" style="margin-top: 8px">
          <el-form-item label="计划日期">
            <el-select
              v-model="autoConfig.planDate"
              :disabled="!autoConfig.startStatus"
              placeholder="请选择计划日期"
              clearable
              @change="handleClickAuto"
              class="!w-240px"
            >
              <el-option
                v-for="option in planDateOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5.5" style="margin-top: 8px">
          <el-form-item label="检察员">
            <el-select
              v-model="autoConfig.checkUserId"
              :disabled="!autoConfig.startStatus"
              placeholder="请选择检察员"
              clearable
              @change="handleClickAuto"
              class="!w-240px"
            >
              <el-option
                v-for="dict in planPersonOption"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5.5" style="margin-top: 11px">
          <span>(*自动创建的检查计划，覆盖所有物资柜)</span>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="计划编号" align="center" prop="id" />
      <el-table-column label="计划名称" align="center" prop="planName" width="220"/>
      <el-table-column label="物资柜" align="center" prop="cabinetName">
<!--        <template #default="scope">-->
<!--          <el-tooltip :content="scope.row.cabinetName" placement="top">-->
<!--            <span class="text-primary cursor-pointer" @click="handlePlanDetail(scope.row)">-->
<!--              {{ getDisplayText(scope.row.cabinetName) }}-->
<!--            </span>-->
<!--          </el-tooltip>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="计划日期" align="center" prop="planDate" />
      <el-table-column label="检察员" align="center" prop="checkUserName" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CHECKING_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="检查记录" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleViewRecord(scope.row)"> 查看 </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            :disabled="scope.row.status === '1'"
            @click="openForm('update', scope.row)"
            v-hasPermi="['iscs:plan:update']"
          >
            修改
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iscs:plan:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-model:total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PlanForm ref="formRef" @success="getList" />

  <!-- 物资柜详情弹窗 -->
  <PlanDetailDialog ref="detailRef" />

  <!-- 检查记录弹窗 -->
  <CheckRecordDialog ref="recordRef" />
</template>

<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import * as PlanApi from '@/api/material/plan'
import * as CabinetApi from '@/api/material/lockers/index'
import * as UserApi from '@/api/system/user'

import PlanForm from './PlanForm.vue'
import PlanDetailDialog from './PlanDetailDialog.vue'
import CheckRecordDialog from './CheckRecordDialog.vue'
import {getDateRange} from "@/utils/formatTime";
import {selectIsMailNotifyConfigByCode} from "@/api/material/plan";


defineOptions({ name: 'InspectionPlan' })
// 在 setup 中定义
const route = useRoute()
const router = useRouter()
const emit = defineEmits<{
  planId: [planId: string | number]
}>()
const props = defineProps({
  cabinetId: {
    type: String,
    required: false
  }
})

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const cabinets = ref([]) // 物资柜数据
const planPersonOption = ref([]) // 检察员选项
const visibleSelect = ref(false) // 是否显示物资柜选择

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  checkUserName: undefined,
  planName: undefined,
  cabinetId: undefined,
  startTime: undefined,
  endTime: undefined,
  status: undefined
})

const createTime = ref(null) // 计划日期
const queryFormRef = ref() // 搜索的表单

// 自动配置
const autoConfig = reactive({
  planFrequency: null,
  planDate: null,
  checkUserId: null,
  startStatus: false,
  templateCode: 'CHECK_PLAN'
})

const planDateOptions = ref([]) // 计划日期选项

/** 查询检查计划列表 */
const getList = async () => {
  loading.value = true
  try {
    // 处理时间范围
    if (Array.isArray(createTime.value) && createTime.value.length == 2) {
      const [startTime, endTime] = getDateRange(createTime.value[0], createTime.value[1])
      queryParams.startTime = startTime
      queryParams.endTime = endTime
    }
    const data = await PlanApi.listPlan(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取物资柜列表 */
const getCabinets = async () => {
  const data = await CabinetApi.listMaterialsCabinet({
    pageNo: 1,
    pageSize: -1
  })
  if (data?.list) {
    cabinets.value = data.list.map((item) => ({
      value: item.id,
      label: item.cabinetName
    }))
  }
}

/** 获取检察员列表  */
const getCheckUsers = async () => {
  const data = await UserApi.getRoleUser('check')
  planPersonOption.value = data.map((item) => ({
    label: item.nickname,
    value: item.id
  }))
}

/** 获取自动配置信息 */
const getAutoConfigInfo = async () => {
  const data = await PlanApi.selectIsMailNotifyConfigByCode({
    templateCode: 'test_01'
  })
  autoConfig.planDate = data.planDate
  autoConfig.planFrequency = data.planFrequency
  autoConfig.checkUserId = data.checkUserId
  autoConfig.startStatus = data.startStatus === '1'
  handleFrequencyChange(data.planFrequency, true)
}

/** 处理频率变更 */
const handleFrequencyChange = (frequency: string, isInitial = false) => {
  if (frequency === '月') {
    planDateOptions.value = Array.from({ length: 31 }, (_, i) => ({
      value: String(i + 1).padStart(2, '0'),
      label: String(i + 1).padStart(2, '0')
    }))
  } else if (frequency === '周') {
    planDateOptions.value = [
      { value: 1, label: '周一' },
      { value: 2, label: '周二' },
      { value: 3, label: '周三' },
      { value: 4, label: '周四' },
      { value: 5, label: '周五' },
      { value: 6, label: '周六' },
      { value: 7, label: '周日' }
    ]
  } else {
    planDateOptions.value = []
  }

  if (!isInitial) {
    autoConfig.planDate = null
  }

  handleClickAuto()
}

/** 处理自动配置变更 */
const handleClickAuto = async () => {
  const data = {
    planFrequency: autoConfig.planFrequency,
    planDate: autoConfig.planDate,
    checkUserId: autoConfig.checkUserId,
    startStatus: autoConfig.startStatus ? 1 : 0,
    templateCode: autoConfig.templateCode
  }
  await PlanApi.updateAutomaticConfig(data)
}

/** 处理状态变更 */
const handleClickStatus = async (value: boolean) => {
  autoConfig.startStatus = value
  await handleClickAuto()
  message.success('更新成功')
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  createTime.value = null
  queryFormRef.value?.resetFields()
  queryParams.startTime = null
  queryParams.endTime = null
  handleQuery()
}



/** 清空时间 */
const handleClearTime = (value: any) => {
  if (value == null) {
    queryParams.startTime = null
    queryParams.endTime = null
  }
}

/** 获取显示文本 */
// const getDisplayText = (cabinetName: string) => {
//   const names = cabinetName.split(',')
//   return `${names.length}个`
// }

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, row?: any) => {
  formRef.value.open(type, row)
}

/** 查看物资柜详情 */
const detailRef = ref()
const handlePlanDetail = (row: any) => {
  detailRef.value.open(row)
}

/** 查看检查记录 */
const recordRef = ref()
const handleViewRecord = (row: any) => {
  if (props.cabinetId) {
    emit('planId', {
      planId: row.id,
      planName: row.planName
    })
  } else {
    router.push({
      path: '/material/material/Inspectionrecords',
      query: {
        planId: row.id,
        planName: row.planName
      }
    })
  }
}

/** 删除按钮操作 */
const handleDelete = async (row: any) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PlanApi.deletePlan(row.id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(async () => {
  queryParams.cabinetId = Number(props.cabinetId) || null
  if (props.cabinetId) {
    visibleSelect.value = true
  }
  await Promise.all([getList(), getCabinets(), getCheckUsers(), getAutoConfigInfo()])
})
</script>

<style lang="scss" scoped>
.text-primary {
  color: var(--el-color-primary);
}

.cursor-pointer {
  cursor: pointer;
}
</style>
