<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">
        <BreadcrumbBack />
        新增责任通知
      </div>
    </header>
    <main class="safety-platform-container__main">
      <el-form ref="formRef" label-width="auto" :model="formValue" :rules="rules">
        <el-form-item label="责任通知名称" prop="responsibilityName">
          <el-input
            v-model="formValue.responsibilityName"
            size="large"
            placeholder="安全责任通知名称"
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item label="责任通知类型">
          <el-radio-group v-model="formValue.type">
            <el-radio :value="1">公共区域</el-radio>
            <el-radio :value="2">非公共区域</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="责任通知附件（非必填）" prop="attachment">
          <UploadFiles
            label="上传附件"
            :maxCount="1"
            @uploadSuccess="handleUploadSuccess"
            :fileList="formValue.attachment"
          />
        </el-form-item>

        <el-form-item label="责任通知内容" prop="content">
          <div class="editor-container">
            <Toolbar style="border-bottom: 1px solid #dcdfe6" :editor="editorRef" />
            <Editor
              style="height: 300px; overflow-y: auto"
              v-model="formValue.content"
              mode="default"
              :default-config="editorConfig"
              @on-created="handleCreated"
              @on-change="handleEditorChange"
            />
          </div>
        </el-form-item>
        <!-- <el-form-item label=" ">
          <el-checkbox v-model="formValue.executeObject" label="创建下发执行对象" @change="handleExecuteObjectChange" />
        </el-form-item> -->
        <!-- <template v-if="Boolean(formValue.executeObject)">
          <el-form-item label="通知区域" prop="safetyAreaData">
            <el-button @click="handleAddArea" type="primary">添加</el-button>
            <el-table :data="currentTableData" v-if="formValue.safetyAreaData.length" style="margin: 20px 0 0">
              <el-table-column v-if="formValue.type === 2" label="楼号" prop="buildingNo" width="180" />
              <el-table-column label="楼层" prop="buildingArea" width="100" />

              <el-table-column label="楼宇/区域" prop="buildingCode" width="180" />
              <el-table-column label="房间/区域" prop="floorRoomNo" width="180" />
              <el-table-column label="功能名称" prop="nameFunction" width="120" />
              <el-table-column label="安全责任所/中心" prop="safetyResponsibleCenter" width="200" />
              <el-table-column label="安全责任所/中心负责人" prop="safetyCenterManagerName" width="200" />
              <el-table-column label="安全责任部门" prop="safetyResponsibleDepartment" width="180" />
              <el-table-column label="安全责任部门负责人" prop="safetyDepartmentManagerName" width="180" />
              <el-table-column label="安全具体责任人" prop="safetySpecificPersonName" width="180" />
              <el-table-column label="安全具体责任人联系方式" prop="safetyPersonContact" width="230" />
              <el-table-column label="状态" prop="statusName" width="100" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button type="text" size="small" @click="handleDeleteArea(scope)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container" v-if="formValue.safetyAreaData.length">
              <el-pagination
                background
                :current-page="queryParams.pageNumber"
                :page-size="queryParams.pageSize"
                :total="formValue.safetyAreaData.length"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-form-item>
          <el-form-item label="计划开始日期" prop="planStartTime">
            <el-date-picker
              v-model="formValue.planStartTime"
              size="large"
              placeholder="请选择日期"
              style="width: 50%"
            />
          </el-form-item>

          <el-form-item label="计划结束日期" prop="planEndTime">
            <el-date-picker v-model="formValue.planEndTime" size="large" placeholder="请选择日期" style="width: 50%" />
          </el-form-item>
        </template> -->
      </el-form>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="$router.push({ name: 'responsibilityNoticeManage:admin' })">返回</el-button>
      <el-button type="primary" @click="handleSubmit" @close="handleCloseAreaDialog" :loading="submiting"
        >提交</el-button
      >
    </footer>
  </div>
  <SelectNotifyArea
    v-if="selectNotifyAreaOpen"
    v-model.visible="selectNotifyAreaOpen"
    :type="formValue.type"
    @submit="handleSelectionTableData"
  />
</template>
<script lang="ts" setup>
  import { onMounted, ref, nextTick, reactive, watch, shallowRef } from 'vue';
  import dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  import { uniqBy, omit } from 'lodash-es';

  import '@wangeditor/editor/dist/css/style.css';
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  import { useRouter, useRoute } from 'vue-router';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import { safetyNoticeAdminSaveSafetyNotice } from '@/api/production-safety/responsibility-implementation';
  import { formatAttachmentList } from '@/components/UploadFiles/utils';
  import SelectNotifyArea from './components/SelectNotifyArea.vue';

  const router = useRouter();
  const route = useRoute();
  const formRef = ref<any>(null);
  const editorRef = shallowRef();
  const submiting = ref(false);
  const selectNotifyAreaOpen = ref(false);
  const editorConfig = {
    placeholder: '请输入...',
  };

  const queryParams = reactive<any>({
    pageNumber: 1,
    pageSize: 3,
  });
  const tableData = reactive<any>({
    data: [],
    total: 0,
  });

  const currentTableData = ref([]);

  const formValue = reactive({
    responsibilityName: '', // 责任通知名称
    type: Number(route.query.areaType) || 1, // 1公共区域2非公共区域
    content: '', // 责任通知内容
    safetyAreaData: [], // 区域分组,多个用，分隔
    attachment: [], // 附件
    planStartTime: null, // 计划开始日期
    planEndTime: null, // 计划结束日期
    status: '', // 1未下发2待反馈3待审核4已完成5已作废
    executeObject: 0, // 是否创建执行对象（0否1是）
  });

  const rules = reactive({
    responsibilityName: [
      {
        required: true,
        message: '责任书名称不能为空',
        trigger: 'change',
      },
    ],
    type: [
      {
        required: true,
        message: '请选择类型',
      },
    ],
    // attachment: [
    //   {
    //     required: true,
    //     message: '请上传附件',
    //   },
    // ],

    content: [
      {
        required: true,
        message: '请输入责任书内容',
      },
      {
        validator: (rule, value, callback) => {
          const text = (value || '').replace(/<[^>]+>/g, '').trim();
          callback(text ? undefined : new Error('责任书内容不能为空'));
        },
        trigger: 'change',
      },
    ],
    planStartTime: [
      {
        required: true,
        message: '请选择计划开始时间',
        trigger: 'change',
      },
      {
        validator: (rule, value, callback) => {
          if (value && formValue.planEndTime) {
            if (dayjs(value).isAfter(formValue.planEndTime)) {
              callback(new Error('开始日期不能大于结束日期'));
              return;
            }
          }
          callback();
        },
      },
    ],
    planEndTime: [
      {
        required: true,
        message: '请选择计划结束时间',
        trigger: 'change',
      },
      {
        validator: (rule, value, callback) => {
          if (value && formValue.planStartTime) {
            if (dayjs(value).isBefore(formValue.planStartTime)) {
              callback(new Error('结束日期不能小于开始日期'));
              return;
            }
          }
          callback();
        },
      },
    ],
    safetyAreaData: [
      {
        required: true,
        message: '请选择区域',
        trigger: 'change',
      },
      {
        validator: (rule, value, callback) => {
          if (value.length === 0) {
            callback(new Error('区域不能为空'));
          }
          callback();
        },
      },
    ],
  });
  const handleDeleteArea = (scope) => {
    formValue.safetyAreaData = formValue.safetyAreaData.filter((item: any) => item.id !== scope.row.id);
    const totalPages = Math.ceil(formValue.safetyAreaData.length / queryParams.pageSize);
    if (queryParams.pageNumber > totalPages) {
      queryParams.pageNumber = totalPages || 1;
    }
    displayData(queryParams.pageNumber);
  };
  const displayData = (page = 1) => {
    const start = (page - 1) * queryParams.pageSize;
    const end = start + queryParams.pageSize;
    currentTableData.value = formValue.safetyAreaData.slice(start, end);
  };
  const handleCurrentChange = (page: number) => {
    queryParams.pageNumber = page;
    displayData(page);
  };

  const handleSizeChange = (size: number) => {
    queryParams.pageSize = size;
  };

  const handleSelectionTableData = (data) => {
    tableData.total = data.length;
    tableData.data = [...tableData.data, ...data];
    Object.assign(formValue, {
      safetyAreaData: uniqBy(tableData.data, 'id'),
    });
    formRef.value?.validateField('safetyAreaData');
    displayData();
  };
  const handleAddArea = () => {
    selectNotifyAreaOpen.value = true;
  };

  const handleCloseAreaDialog = () => {
    selectNotifyAreaOpen.value = false;
  };

  const handleCreated = (value) => {
    editorRef.value = value;
  };

  const handleEditorChange = (editor) => {
    formValue.content = editor.getHtml();
    if (!formValue.content.replace(/<[^>]+>/g, '').trim()) {
      return;
    }
    nextTick(() => {
      formRef.value?.validateField('content');
    });
  };

  const handleUploadSuccess = (fileList) => {
    formValue.attachment = fileList;
    formRef.value.validateField('attachment');
  };
  const handleExecuteObjectChange = (value) => {
    if (!value) {
      Object.assign(formValue, {
        planStartTime: null,
        planEndTime: null,
      });
    }
  };
  const handleSubmit = () => {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        submiting.value = true;
        const attachment = await formatAttachmentList(formValue.attachment);
        safetyNoticeAdminSaveSafetyNotice({
          ...omit(formValue, 'safetyAreaData'),
          planStartTime: formValue.planStartTime ? dayjs(formValue.planStartTime).format('YYYY-MM-DD') : null,
          planEndTime: formValue.planEndTime ? dayjs(formValue.planEndTime).format('YYYY-MM-DD') : null,
          attachment: JSON.stringify(attachment),
          executeObject: Number(formValue.executeObject),
          safetyAreaId: formValue.safetyAreaData.map((item: any) => item.id).join(','),
        })
          .then(() => {
            ElMessage.success('创建成功!');
            router.push({
              name: 'responsibilityNoticeManage:admin',
            });
          })
          .finally(() => {
            submiting.value = false;
          });
      } else {
      }
    });
  };
  watch(
    () => [formValue.type, formValue.executeObject],
    () => {
      tableData.data = [];
      formValue.safetyAreaData = [];
      currentTableData.value = [];
      queryParams.pageNumber = 1;
      queryParams.pageSize = 3;
    },
  );
  onMounted(() => {});
</script>

<style lang="scss" scoped>
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  .editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-right: 20px;
    overflow: hidden;
  }
  .pagination-container {
    margin-top: 20px;
  }
</style>
