<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

// @ts-ignore
import { useVbenDrawer, useVbenForm } from '@vben/common-ui';
import { useAccessStore } from '@vben/stores';

import { Plus } from '@element-plus/icons-vue';
import { ElIcon, ElUpload } from 'element-plus';

import { selectAllSysStation } from '#/api/system/infoEntry/stationInfo/stationInfo';
import { stationoperatorapi } from '#/api/system/tasksettings/tasktemplate';
// import '#/assets/iconfonts/font/iconfont.css';
import iconfont from '#/assets/iconfonts/font/iconfont.json';
import TinymceEditor from '#/components/tinymce/src/editor.vue';
import { getUploadAction } from '#/components/upload/config';

import { drawerFormSchema } from './taskTemplate-data';

const emit = defineEmits(['Confirm']);
const iconlist = ref(iconfont?.glyphs || []);
const accessStore = useAccessStore();
const isUpdateRef = ref<boolean>(false);
const isViewRef = ref<boolean>(false);
const isCopyRef = ref<boolean>(false);

// 附件列表 - 添加类型定义
const attachments = ref<any[]>([]);
const selectAllSysStationList = ref([]) as any;
onMounted(async () => {
  const res = await selectAllSysStation();
  selectAllSysStationList.value = res || [];
  if (selectAllSysStationList.value.length > 0) {
    selectAllSysStationList.value.forEach((item: any) => {
      item.isExecutable = true; // 是否执行
      item.isLicensable = false; // 是否授权
    });
  }
});
// 定义抽屉数据类型
interface DrawerData {
  id?: string;
  taskName?: string;
  isUpdate?: boolean;
  isView?: boolean;
  isCopy?: boolean;
  attachment?: any[];
  [key: string]: any;
}
const radio1 = ref('');
const dialogVisible = ref(false);
const selectedIcon = ref('');
const taskFrequency = ref('');
const isWebmaster = ref(false);

// // 处理taskFrequency变化的函数
const formOptions = computed(() => {
  return {
    showDefaultActions: false,
    // schema: drawerFormSchema(),
    // @ts-ignore
    schema: drawerFormSchema({
      handleTaskFrequencyChange,
    }),
    isDisabled: isViewRef.value,
    wrapperClass: 'grid-cols-2',
    handleValuesChange: (values: any) => {
      if (values.executePosition === 3) {
        radio1.value = '0';
        isWebmaster.value = true;
      }
    },
  };
});
const handleTaskFrequencyChange = (value: string) => {
  taskFrequency.value = value;
};
// 每天一次 daily
// 每周一次 weekly
// 每月一次 monthly
// 每两月一次 every_two_months
// 每三月一次 every_three_months
// 每六月一次 every_six_months
// 每年一次 yearly
// const startTimeDayOptions = ref<any[]>([]);
// const endTimeDayOptions = ref<any[]>([]);
// const startTimeHourOptions = ref<any[]>([]);
// const endTimeHourOptions = ref<any[]>([]);
// watch(
//   () => taskFrequency.value,
//   (newValue) => {
//     if (newValue === 'daily') {
//       startTimeDayOptions.value = [
//         {
//           label: '每天一次',
//           value: 'daily',
//         },
//       ];
//       endTimeDayOptions.value = [];
//       startTimeHourOptions.value = [];
//       endTimeHourOptions.value = [];
//     } else if (newValue === 'weekly') {
//       startTimeDayOptions.value = [
//         {
//           label: '每周一次',
//           value: 'weekly',
//         },
//       ];
//       endTimeDayOptions.value = [];
//       startTimeHourOptions.value = [];
//       endTimeHourOptions.value = [];
//     } else if (newValue === 'monthly') {
//       startTimeDayOptions.value = [
//         {
//           label: '每月一次',
//           value: 'monthly',
//         },
//       ];
//       endTimeDayOptions.value = [];
//       startTimeHourOptions.value = [];
//       endTimeHourOptions.value = [];
//     } else if (newValue === 'every_two_months') {
//       startTimeDayOptions.value = [
//         {
//           label: '每两月一次',
//           value: 'every_two_months',
//         },
//       ];
//       endTimeDayOptions.value = [];
//       startTimeHourOptions.value = [];
//       endTimeHourOptions.value = [];
//     } else if (newValue === 'every_three_months') {
//       startTimeDayOptions.value = [
//         {
//           label: '每三月一次',
//           value: 'every_three_months',
//         },
//       ];
//       endTimeDayOptions.value = [];
//       startTimeHourOptions.value = [];
//       endTimeHourOptions.value = [];
//     } else if (newValue === 'every_six_months') {
//       startTimeDayOptions.value = [
//         {
//           label: '每六月一次',
//           value: 'every_six_months',
//         },
//       ];
//       endTimeDayOptions.value = [];
//       startTimeHourOptions.value = [];
//       endTimeHourOptions.value = [];
//     } else if (newValue === 'yearly') {
//       startTimeDayOptions.value = [
//         {
//           label: '每年一次',
//           value: 'yearly',
//         },
//       ];
//       endTimeDayOptions.value = [];
//       startTimeHourOptions.value = [];
//       endTimeHourOptions.value = [];
//     } else {
//       startTimeDayOptions.value = [];
//     }
//   },
//   { immediate: true }, // 立即执行一次，设置初始值
// );
// watch(
//   () => taskFrequency.value,
//   (newValue) => {
//     console.log('taskFrequency changed:', newValue);
//   },
// );
const [Form, formApi] = useVbenForm(formOptions.value);

// 存储表单值的响应式变量
const formValues = ref({});

// 更新表单值的函数
// const updateFormValues = async () => {
//   try {
//     formValues.value = await formApi.getValues();
//   } catch (error) {
//     console.error('获取表单值失败:', error);
//   }
// };

// // 监听表单值变化
// Form.onValuesChange(() => {
//   updateFormValues();
// });

// // 初始化时获取表单值
// updateFormValues();

const drawerTitle = computed(() => {
  if (isViewRef.value) return '查看任务';
  if (isUpdateRef.value) return '编辑任务';
  if (isCopyRef.value) return '复制任务';
  return '新增任务';
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: any) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const data = drawerApi.getData() as DrawerData;
      // 更新状态
      isUpdateRef.value = !!data.isUpdate;
      isViewRef.value = !!data.isView;
      isCopyRef.value = !!data.isCopy;
      // 更新表单配置
      // formApi.setOptions(formOptions.value);
      if ((isUpdateRef.value || isViewRef.value) && data.id) {
        // console.log('isUpdateRef.value', isUpdateRef.value);
        // console.log('isViewRef.value', isViewRef.value);
        // console.log('编辑或查看模式', data);
        console.log('data', data);
        if (data.executePosition) {
          data.executePositions = data.executePosition
            .toString()
            .split(',')
            .map((item: any) => Number(item.trim()));
        }
        data.isTiming = data.isTiming.toString();
        console.log('data.isTiming', data.isTiming);
        await formApi.setValues(data);
        radio1.value = String(data.distributionMethod);
        // 初始化taskFrequency值
        if (data.taskFrequency) {
          taskFrequency.value = data.taskFrequency;
        }
        if (radio1.value == '0') {
          // 为所有站点设置isExecutable属性
          selectAllSysStationList.value.forEach((station: any) => {
            const isInTask =
              data.taskTemplateStations &&
              data.taskTemplateStations.some(
                (item: any) => item.stationId == station.id,
              );
            station.isExecutable = isInTask;
          });

          if (data.taskTemplateStations) {
            // 预加载所有站点的操作人员数据
            const loadStationOperators = async () => {
              for (const item of data.taskTemplateStations) {
                const stationIndex = selectAllSysStationList.value.findIndex(
                  (station: any) => station.id == item.stationId,
                );
                if (stationIndex !== -1) {
                  try {
                    // 加载站点操作人员数据
                    const res = await stationoperatorapi({
                      stationId: item.stationId,
                    });
                    selectAllSysStationList.value[
                      stationIndex
                    ].taskTemplateUsersoption = res;

                    // 更新现有站点数据
                    selectAllSysStationList.value[stationIndex].isLicensable =
                      item.isLicensable == '1';
                    selectAllSysStationList.value[
                      stationIndex
                    ].taskTemplateUsers = item.taskTemplateUsers || [];
                    // 设置选中的用户
                    if (
                      item.taskTemplateUsers &&
                      item.taskTemplateUsers.length > 0
                    ) {
                      selectAllSysStationList.value[stationIndex].value1 =
                        item.taskTemplateUsers.map((user: any) => user.userId);
                    }
                  } catch (error) {
                    console.log('加载站点操作人员数据失败:', error);
                  }
                }
              }
            };

            // 执行加载操作
            loadStationOperators();
          }
        }
        selectedIcon.value = data.icon || '';
        attachments.value = data.filesUrl.map((item: any) => {
          return {
            name: item.split('/').pop()!.split('?')[0].replace(/%3F.*/, ''),
            response: {
              code: 200,
              data: {
                fileName: item
                  .split('/')
                  .pop()!
                  .split('?')[0]
                  .replace(/%3F.*/, ''),
                url: item,
              },
            },
            uid: Date.now().toString(36) + Math.random().toString(36).slice(2),
          };
        });
      } else if (isCopyRef.value) {
        // 复制模式
        await formApi.setValues({
          id: '',
          taskName: data.taskName ? `${data.taskName}（副本）` : '',
        });
        // 清空附件
        attachments.value = [];
        // 清空选中的图标
        selectedIcon.value = '';
        // 同步taskFrequency值
        const formValues = await formApi.getValues();
        taskFrequency.value = formValues.taskFrequency || '';
      } else {
        const formValues = await formApi.getValues();
        taskFrequency.value = formValues.taskFrequency || '';
      }
    } catch (error) {
      console.error('获取任务详情失败:', error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },

  async onConfirm() {
    try {
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const formData = await formApi.getValues();

      // 添加附件数据
      if (attachments.value.length > 0) {
        formData.attachment = attachments.value;
      }
      if (radio1.value === '0') {
        formData.distributionMethod = '0';
        if (selectAllSysStationList.value.length > 0) {
          const ExecutableList = selectAllSysStationList.value.filter(
            (item: any) => item.isExecutable,
          );
          if (ExecutableList.length > 0) {
            formData.taskTemplateStations = ExecutableList.map((item: any) => {
              return {
                isLicensable: item.isLicensable === false ? '0' : '1',
                stationId: item.id,
                taskTemplateUsers: item?.taskTemplateUsers || [],
              };
            });
          }
        }
      } else if (radio1.value === '1') {
        formData.distributionMethod = '1';
      }
      emit('Confirm', formData);
    } catch (error) {
      console.error('保存任务信息失败:', error);
    }
  },

  onClosed() {
    // 重置表单和状态
    formApi.resetForm();
    isUpdateRef.value = false;
    isViewRef.value = false;
    isCopyRef.value = false;
    attachments.value = [];
    radio1.value = '';
  },
});

// 上传文件处理
const handleUpload = (options: any, file: any, fileList: any[]) => {
  console.log('上传文件', attachments.value);

  if (options.code === 200) {
    console.log('文件上传成功:', options.data);
  }
};

// 移除文件处理
const handleRemove = (file: any, fileList: any[]) => {
  attachments.value = fileList;
};
const handleChangeselect = (val: any) => {
  const index = selectAllSysStationList.value.findIndex(
    (item: any) => item.id == val.id,
  );
  const taskTemplateUsers = val.taskTemplateUsersoption.filter((item: any) => {
    for (let i = 0; i < val.value1.length; i++) {
      if (item.userId === val.value1[i]) {
        return true;
      }
    }
  });
  if (index !== -1) {
    selectAllSysStationList.value[index].taskTemplateUsers =
      taskTemplateUsers.map((item: any) => {
        return {
          stationId: item.stationId,
          userId: item.userId,
        };
      });
  }
};
const handlevisibleselect = async (row: any) => {
  try {
    // 避免重复请求
    if (!row.taskTemplateUsersoption) {
      const res = await stationoperatorapi({ stationId: row.id });
      const index = selectAllSysStationList.value.findIndex(
        (item: any) => item.id == row.id,
      );
      if (index !== -1) {
        selectAllSysStationList.value[index].taskTemplateUsersoption = res;
      }
    }
  } catch (error) {
    console.log('加载站点操作人员数据失败:', error);
  }
};
const selectIcon = (val: any, item: any) => {
  formApi.setFieldValue('icon', item.font_class);
  selectedIcon.value = item.font_class;
  // console.log(formApi.getValues());
};
</script>

<template>
  <Drawer :title="drawerTitle" :show-confirm-button="!isViewRef">
    <Form>
      <!-- 自定义Tinymce编辑器插槽 -->
      <template #description="scope">
        <TinymceEditor
          :model-value="scope.modelValue"
          @update:model-value="
            (val: string) => scope['onUpdate:modelValue'](val)
          "
          :height="400"
          :options="{ auto_focus: 'false' }"
        />
      </template>
      <!-- // postId 1  管理部
// postId 2  片区经理
// postId 3  站长
// postId 4  当班经理
// postId 5  测试
// postId 6  安全管理部 -->
      <!-- v-if="formApi.getValues().then(res)=>res.executePosition==='0'" -->
      <template #distributionMethod="scope">
        <div style="display: flex; gap: 16px; align-items: center">
          <!-- <button @click=" ()=>{
        
            console.log('executePosition:',formValues );
          }">按钮</button> -->
          <div>
            <el-radio-group v-model="radio1">
              <el-radio value="0" size="large">场站</el-radio>
              <el-radio :disabled="isWebmaster" value="1" size="large">
                岗位
              </el-radio>
            </el-radio-group>
          </div>
          <div>
            <el-button v-if="radio1 === '0'" @click="dialogVisible = true">
              配置
            </el-button>
          </div>
        </div>
        <div>
          <el-dialog v-model="dialogVisible" title="执行场站" width="1000">
            <div>
              <el-button
                type="primary"
                plain
                @click="
                  selectAllSysStationList.forEach(
                    (item: any) => (item.isExecutable = !item.isExecutable),
                  )
                "
              >
                全部可执行
              </el-button>
              <el-button
                type="primary"
                plain
                @click="
                  selectAllSysStationList.forEach(
                    (item: any) => (item.isLicensable = !item.isLicensable),
                  )
                "
              >
                全部可授权
              </el-button>
            </div>
            <el-table :data="selectAllSysStationList" style="width: 100%">
              <el-table-column prop="stationName" label="场站" width="180" />
              <el-table-column label="是否执行" width="180">
                <template #default="{ row }">
                  <el-checkbox v-model="row.isExecutable" size="large" />
                </template>
              </el-table-column>
              <el-table-column label="是否授权">
                <template #default="{ row }">
                  <el-checkbox v-model="row.isLicensable" size="large" />
                </template>
              </el-table-column>
              <el-table-column prop="address" label="执行人" width="270">
                <template #default="{ row }">
                  <el-select
                    v-model="row.value1"
                    multiple
                    placeholder="请选择执行人"
                    style="width: 240px"
                    @change="() => handleChangeselect(row)"
                    @visible-change="
                      (visible: any) => visible && handlevisibleselect(row)
                    "
                  >
                    <el-option
                      v-for="item in row.taskTemplateUsersoption"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.userId"
                    />
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
            <template #footer>
              <div class="dialog-footer"></div>
            </template>
          </el-dialog>
        </div>
      </template>
      <template #icon="scope">
        <div class="icon-box">
          <div
            class="icon-item"
            :class="{
              'icon-item-active': item.font_class === selectedIcon,
            }"
            @click="() => selectIcon(scope, item)"
            v-for="item in iconlist"
            :key="item.icon_id"
          >
            <svg class="icon" aria-hidden="true">
              <use :href="`#icon-${item.font_class}`" />
            </svg>
          </div>
        </div>
      </template>

      <!-- <template #startTimeDay="scope">
        <el-select
          v-model="scope.modelValue"
          placeholder="Select"
          style="width: 240px"
        >
          <el-option
            v-for="item in startTimeDayOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template> -->
      <!-- <template #startTimeHour="scope">
        <el-select
          v-model="scope.modelValue"
          placeholder="Select"
          style="width: 240px"
        >
          <el-option
            v-for="item in startTimeHourOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </template> -->
      <!-- <template #endTimeDay="scope">
        <el-select
          v-model="scope.modelValue"
          placeholder="Select"
          style="width: 240px"
        >
          <el-option
            v-for="item in endTimeDayOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template> -->
      <!-- <template #endTimeHour="scope">
        <el-select
          v-model="scope.modelValue"
          placeholder="Select"
          style="width: 240px"
        >
          <el-option
            v-for="item in endTimeHourOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template> -->
      <!-- 自定义附件上传插槽 -->
      <template #attachment="scope">
        <ElUpload
          v-model:file-list="attachments"
          :action="getUploadAction()"
          :headers="{ Authorization: `Bearer ${accessStore.accessToken}` }"
          accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
          list-type="text"
          show-file-list
          :auto-upload="true"
          :drag="false"
          :limit="5"
          :on-success="handleUpload"
          :on-remove="handleRemove"
          class="task-attachment-upload"
        >
          <div class="upload-container">
            <div class="upload-icon">
              <ElIcon>
                <Plus size="40" />
              </ElIcon>
            </div>
            <div class="upload-content">
              <div class="upload-title">点击上传文件</div>
              <div class="upload-desc">或拖拽文件到此处</div>
              <div class="upload-tip">
                <span class="tip-limit">最多可上传5个文件</span>
                <span class="tip-types"
                  >支持格式：图片、PDF、Word、Excel、PPT</span
                >
              </div>
            </div>
          </div>
        </ElUpload>
      </template>
    </Form>
  </Drawer>
</template>

<style scoped>
.icon-box {
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.icon-item {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #d9d9d9;
  box-sizing: border-box;
  /* border: 1px solid red; */
}
.icon-item-active {
  border: 1px solid #409eff;
  box-sizing: border-box;
}
.icon {
  padding: 8px;
  width: 50px;
  height: 50px;
}
.task-attachment-upload {
  width: 100%;
}

.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 20px;
  background-color: #fafafa;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  transition: all 0.3s;
}

.upload-container:hover {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.upload-icon {
  margin-bottom: 15px;
  color: #409eff;
}

.upload-content {
  text-align: center;
}

.upload-title {
  margin-bottom: 5px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.upload-desc {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.upload-tip {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.tip-limit,
.tip-types {
  display: inline-block;
}

/* 确保表单标题不换行 */
:deep(.vben-form-item__label),
:deep(.el-form-item__label),
:deep(.form-item__label),
:deep(
  .text-sm.font-medium.peer-disabled\:cursor-not-allowed.peer-disabled\:opacity-70.items-center.flex.leading-6.mr-2.flex-shrink-0.justify-end
) {
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  min-width: 120px !important;
  width: 120px !important;
}
</style>
