<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">
        <BreadcrumbBack />
        {{ $route?.meta?.title }}
      </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="类别名称" prop="departmentName">
          <el-select v-model="formValue.departmentName" size="large" placeholder="类别名称" style="width: 50%">
            <el-option value="院领导">院领导</el-option>
            <el-option value="所/中心/职能部门/直属研究部/分公司">所/中心/职能部门/直属研究部/分公司</el-option>
            <el-option value="所/中心级部门">所/中心级部门</el-option>
            <el-option value="科室">科室</el-option>
            <el-option value="员工">员工</el-option>
            <el-option value="常驻供应商">常驻供应商</el-option>
          </el-select>
        </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="userGroupId">
            <el-select v-model="formValue.userGroupId" multiple size="large" placeholder="分组名称" style="width: 50%">
              <el-option v-for="group in groupList" :key="group.id" :label="group.name" :value="group.id" />
            </el-select>
          </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>
          <el-form-item label="是否推送" prop="isUrgent">
            <el-radio-group v-model="formValue.isUrgent">
              <el-radio :value="0">否</el-radio>
              <el-radio :value="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </template> -->
      </el-form>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="$router.push({ name: 'responsibilityAgreeManage' })">返回</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submiting">提交</el-button>
    </footer>
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, nextTick, reactive, shallowRef } from 'vue';
  import dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  // @ts-ignore: missing type declarations for CSS side-effect import
  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 { queryUserGroupPage } from '@/api/system/person-group';
  import { safetyResponsibilitySaveSafetyResponsibility } from '@/api/production-safety/responsibility-implementation';
  import { formatAttachmentList } from '@/components/UploadFiles/utils';

  const router = useRouter();
  const route = useRoute();
  const formRef = ref<any>(null);
  const editorRef = shallowRef();
  const submiting = ref(false);
  const editorConfig = {
    placeholder: '请输入...',
  };
  const groupList = ref<any>([]);
  const formValue = reactive({
    responsibilityName: '',
    departmentName: '',
    userGroupId: [],
    planStartTime: null,
    planEndTime: null,
    isUrgent: 0,
    executeObject: 0,
    content: '<p></p>',
    attachment: [],
  });

  const rules = reactive({
    responsibilityName: [
      {
        required: true,
        message: '责任书名称不能为空',
        trigger: 'change',
      },
    ],
    departmentName: [
      {
        required: true,
        message: '请选择部门',
        trigger: 'change',
      },
    ],
    attachment: [
      {
        required: true,
        message: '请上传附件',
      },
    ],
    userGroupId: [
      {
        required: true,
        message: '请选择分组',
        trigger: 'change',
      },
    ],
    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();
        },
      },
    ],
    isUrgent: [
      {
        required: true,
        message: '请选择是否推送',
        trigger: 'change',
      },
    ],
  });

  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 handleQueryUserGroupPage = () => {
    queryUserGroupPage({
      pageNumber: 1,
      pageSize: 500,
    }).then((res) => {
      groupList.value = res.records;
    });
  };

  const handleUploadSuccess = (fileList) => {
    formValue.attachment = fileList;
    formRef.value.validateField('attachment');
  };
  const handleExecuteObjectChange = (value) => {
    if (!value) {
      Object.assign(formValue, {
        userGroupId: [],
        planStartTime: null,
        planEndTime: null,
        isUrgent: 0,
      });
    }
  };
  const handleSubmit = () => {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        submiting.value = true;
        const attachment = await formatAttachmentList(formValue.attachment);
        safetyResponsibilitySaveSafetyResponsibility({
          ...formValue,
          // 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),
          userGroupId: formValue.userGroupId.join(','),
        })
          .then((res) => {
            ElMessage.success('创建成功!');
            router.push({
              name: 'responsibilityAgreeManage',
            });
          })
          .finally(() => {
            submiting.value = false;
          });
      } else {
      }
    });
  };
  onMounted(() => {
    handleQueryUserGroupPage();
  });
</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;

    // :deep(.w-e-text-container) {
    //   min-height: 400px;
    //   overflow-y: auto;
    // }
  }
  // :deep(.breadcrumb .title) {
  //   margin-left: 0;
  // }

  // .main {
  //   display: flex;
  //   flex-direction: column;
  //   padding: 20px;
  //   flex: 1;
  //   overflow: hidden;
  //   background-color: #fff;
  // }
  // .button-content {
  //   margin-bottom: 20px;
  // }

  // .page-content {
  //   display: flex;
  //   justify-content: flex-end;
  // }
  // // :deep(.el-form) {
  // //   flex: 1;
  // //   overflow: hidden;
  // //   overflow-y: auto;
  // // }
</style>
