<script setup lang="ts">
import { ElMessage, UploadProps } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";

import WangEditor from "@/components/WangEditor/index.vue";
import { useKnowledgeCentreStoreHooks } from "@/store/modules/knowledgeCentre";
import { message } from "@/utils/message";
import { getUserInfo } from "@/utils/auth";
const ruleFormRef = ref();
const formData = reactive({
  operate: "",
  linkList: [
    {
      linkName: "",
      linkUrl: ""
    }
  ],
  baseId: "",
  execTime: undefined,
  fileIdList: [],
  excerpt: "",
  publishDeptId: "",

  knowledgeInfo: {
    timeliness: undefined,
    execTimeBegin: "",
    execTimeEnd: "",
    autoLoseEffect: undefined,
    territory: "",
    knowledgeTag: "",
    policyType: "",
    publishScope: "",
    publishDate: undefined
  },
  fileList: []
});
let userInfo = reactive({
  username: "",
  deptName: ""
});
defineExpose({
  getDetails(data) {
    refWangEditor.value.initText(data.knowledgeContext.context);
    refWangEditor.value.initTitle(data.knowledge.title);
    const fileIdList = [];
    const fileList = [];
    data.fileInfoList.forEach(e => {
      fileIdList.push(e.fileBlobId);
      fileList.push({
        name: e.fileName
      });
    });
    const { baseId, excerpt, publishDeptId } = data.knowledge;
    const obj = {
      operate: "",
      linkList: data.knowledgeLinkList,
      baseId,
      execTime: [
        data.knowledgeInfo.execTimeBegin,
        data.knowledgeInfo.execTimeEnd
      ],
      fileIdList,
      excerpt,
      publishDeptId,
      knowledgeInfo: data.knowledgeInfo,
      fileList
    };
    for (const key in obj) {
      // eslint-disable-next-line no-prototype-builtins
      if (formData.hasOwnProperty(key)) {
        formData[key] = obj[key];
      }
    }
    console.log(formData);
  }
});
const departmentList = computed(() => {
  return useKnowledgeCentreStoreHooks().departmentList;
});
const applicationSubLibrary = computed(() => {
  return useKnowledgeCentreStoreHooks().applicationSubLibrary;
});
const refWangEditor = ref();
const rules = {
  publishDeptId: [{ required: true, message: "请选择", trigger: "change" }],
  baseId: [{ required: true, message: "请选择", trigger: "change" }],
  "knowledgeInfo.publishDate": [
    { required: true, message: "请选择", trigger: "change" }
  ],
  "knowledgeInfo.timeliness": [
    { required: true, message: "请选择", trigger: "change" }
  ]
};

const handleSuccess: UploadProps["onSuccess"] = response => {
  if (response.code === 200) {
    formData.fileIdList.push(response.data);
  }
};
const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
  const list = [];
  for (const item of uploadFiles) {
    list.push(item.response.data);
  }
  formData.fileIdList = list;
};
const beforeUpload: UploadProps["beforeUpload"] = async rawFile => {
  //上传图片格式和大小要求  png|jpg  10M

  const type = rawFile.name.split(".")[rawFile.name.split(".").length - 1];
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("大小不能大于10M");
    return false;
  }
  // fileInfo.fileName = rawFile.name;
  return true;
};
const addUrl = () => {
  formData.linkList.push({
    linkName: "",
    linkUrl: ""
  });
};
const delUrl = index => {
  formData.linkList.splice(index, 1);
};
const emit = defineEmits(["save"]);
const save = async (type, formEl) => {
  if (!refWangEditor.value.title || !refWangEditor.value.valueHtml) {
    message("请填写标题和正文", { type: "error" });
    return;
  }
  const { excerpt, fileIdList, linkList, publishDeptId, execTime, baseId } =
    formData;
  if (execTime && execTime.length > 0) {
    formData.knowledgeInfo.execTimeBegin = execTime[0];
    formData.knowledgeInfo.execTimeEnd = execTime[1];
  }
  const params = {
    operate: type,
    title: refWangEditor.value.title,
    content: refWangEditor.value.valueHtml,
    excerpt,
    fileIdList,
    linkList,
    publishDeptId,
    baseId,
    knowledgeInfo: formData.knowledgeInfo
  };

  if (type === 2) {
    formEl.validate(async (valid, fields) => {
      if (valid) {
        emit("save", params);
      } else {
        return fields;
      }
    });
  } else {
    emit("save", params);
  }
};
const changeType = val => {
  if (val === 1) {
    formData.execTime = [];
  }
};
const reset = () => {
  ruleFormRef.value.resetFields();
  formData.linkList = [
    {
      linkName: "",
      linkUrl: ""
    }
  ];
  refWangEditor.value.initText("");
  refWangEditor.value.initTitle("");
};
onMounted(() => {
  const obj: any = getUserInfo();
  userInfo = JSON.parse(obj);
});
</script>

<template>
  <div class="template-submission">
    <el-scrollbar class="main-content" :show-scrollbar="false">
      <el-form
        ref="ruleFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <div class="main-card">
          <div class="main-card-title">
            <span>报送知识</span>
          </div>
          <el-row>
            <el-form-item class="ml-2" label="报送人姓名" prop="username">
              <el-input
                disabled
                v-model="userInfo.username"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item class="ml-8" label="报送人部门" prop="deptName">
              <el-input
                disabled
                v-model="userInfo.deptName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-row>
        </div>
        <div class="Editortext">
          <WangEditor ref="refWangEditor" />
        </div>
        <div class="main-card">
          <el-row>
            <el-col :span="24">
              <el-form-item label="摘要" prop="excerpt">
                <el-input
                  size="large"
                  v-model="formData.excerpt"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="相关附件" prop="fileList">
                <el-upload
                  :file-list="formData.fileList"
                  :limit="5"
                  multiple
                  action="/know-sub/file/upload"
                  :on-success="handleSuccess"
                  :on-remove="handleRemove"
                  :before-upload="beforeUpload"
                >
                  <div class="upload-btn">
                    <el-icon><Plus class="upload-btn-icon" /></el-icon>
                    <span>上传素材</span>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="相关链接">
            <div
              class="url_list"
              v-for="(item, index) in formData.linkList"
              :key="index"
            >
              <el-row class="url_list_item">
                <el-input
                  size="large"
                  style="width: 500px"
                  v-model="formData.linkList[index].linkName"
                  placeholder="请输入链接标题"
                />
                <el-input
                  style="width: 600px; margin-left: 16px"
                  size="large"
                  v-model="formData.linkList[index].linkUrl"
                  placeholder="请输入链接"
                  ><template #append>URL</template></el-input
                >
                <div v-if="index === 0" class="add_url" @click="addUrl">
                  <el-icon><Plus class="upload-btn-icon" /></el-icon>
                  <span>添加链接</span>
                </div>
                <div v-else @click="delUrl(index)" class="del_url">
                  <span>删除</span>
                </div>
              </el-row>
            </div>
          </el-form-item>
        </div>
        <div class="main-card">
          <el-row>
            <el-col :span="24">
              <el-form-item label="发文部门" prop="publishDeptId">
                <el-select
                  size="large"
                  filterable
                  v-model="formData.publishDeptId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in departmentList"
                    :key="item.id"
                    :label="item.deptName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="应用子库" prop="baseId">
                <el-select
                  size="large"
                  filterable
                  v-model="formData.baseId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in applicationSubLibrary"
                    :key="item.id"
                    :label="item.baseName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="发布日期" prop="knowledgeInfo.publishDate">
                <el-date-picker
                  v-model="formData.knowledgeInfo.publishDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择"
                  size="large"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="有效日期" prop="knowledgeInfo.timeliness">
              <el-radio-group
                @change="changeType"
                v-model="formData.knowledgeInfo.timeliness"
                class="ml-4"
              >
                <el-radio :label="1" size="large">长期有效</el-radio>
                <el-radio :label="2" size="large">临时有效</el-radio>
              </el-radio-group>
              <el-date-picker
                v-if="formData.knowledgeInfo.timeliness === 2"
                class="ml-4"
                v-model="formData.execTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="至"
                start-placeholder="有效开始时间"
                end-placeholder="有效结束时间"
                size="large"
              />
              <!-- <el-checkbox
                class="ml-4"
                :true-label="1"
                :false-label="0"
                v-model="formData.knowledgeInfo.autoLoseEffect"
                label="到期自动失效"
                size="large"
              /> -->
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="所属地域" prop="knowledgeInfo.territory">
                <el-input
                  size="large"
                  v-model="formData.knowledgeInfo.territory"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="知识标签" prop="knowledgeInfo.knowledgeTag">
                <el-input
                  size="large"
                  v-model="formData.knowledgeInfo.knowledgeTag"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="政策类型" prop="knowledgeInfo.policyType">
                <el-input
                  size="large"
                  v-model="formData.knowledgeInfo.policyType"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="公开范围" prop="knowledgeInfo.publishScope">
                <el-radio-group
                  v-model="formData.knowledgeInfo.publishScope"
                  class="ml-4"
                >
                  <el-radio :label="0" size="large">公开</el-radio>
                  <el-radio :label="1" size="large">不公开</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </el-scrollbar>

    <div class="footer-content">
      <el-button
        @click="save(2, ruleFormRef)"
        size="large"
        style="width: 150px; height: 50px"
        type="primary"
        >发布</el-button
      >
      <div class="normal_btn" @click="save(1, ruleFormRef)">存草稿</div>
      <span class="reset_btn" @click="reset">重置</span>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.template-submission {
  margin: 0 80px;

  .main-content {
    height: calc(100vh - 280px);
    overflow: auto;
    .main-card {
      width: 100%;

      background: #ffffff;
      border-radius: 6px 6px 6px 6px;
      margin-bottom: 16px;
      padding: 24px;
      .main-card-title {
        margin-bottom: 24px;
        span {
          font-size: 24px;
          color: #333333;
          padding-left: 8px;
          border-left: 6px solid #0052d9;
        }
      }
      .upload-btn {
        width: 140px;
        height: 50px;
        background: #ffffff;
        border-radius: 6px 6px 6px 6px;
        border: 1px solid #0052d9;
        font-size: 16px;
        color: #0052d9;
        display: flex;
        align-items: center;
        justify-content: center;
        .upload-btn-icon {
          color: #0052d9;
        }
      }
    }
  }
  .url_list {
    .url_list_item {
      display: flex;
      margin-bottom: 32px;
      .add_url {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 16px;
        font-size: 16px;
        color: #0052d9;
        cursor: pointer;
      }
      .del_url {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 16px;
        font-size: 16px;
        color: #999999;
        cursor: pointer;
      }
    }
  }
  .footer-content {
    width: 100%;
    height: 99px;
    box-shadow: 0px 0px 16px 0px rgba(0, 0, 0, 0.1);
    background: #ffffff;
    border-radius: 6px 6px 6px 6px;
    display: flex;
    align-items: center;
    flex-direction: row-reverse;
    padding: 24px;
    margin-top: 16px;
    .normal_btn {
      width: 150px;
      height: 50px;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid #0052d9;
      line-height: 50px;
      text-align: center;
      font-size: 16px;
      color: #0052d9;
      margin-right: 40px;
      cursor: pointer;
    }
    .reset_btn {
      margin-right: 40px;
      font-size: 16px;
      color: #999999;
      cursor: pointer;
    }
  }
  .Editortext {
    background: #ffffff;
    border-radius: 6px 6px 6px 6px;
    margin-bottom: 16px;
  }
}
</style>
