<template>
  <div class="addCopyRight">
    <syHeaderNavBar @back="() => $router.back()" @close="() => $router.back()"
      >版权申请
    </syHeaderNavBar>
    <ModuleContainer
      class="mx-auto"
      style="
        margin-top: 17px;
        padding-top: 60px;
        padding-left: 68px;
        padding-right: 68px;
        width: 858px;
      "
    >
      <div class="title text-center" ref="titleRef">填写版权信息</div>
      <div class="tip text-center">请仔细填写作品资料,审核通过后将不能修改</div>
      <AddFilingPerson
        v-model:visible="addFilingPersonVisible"
      ></AddFilingPerson>
      <ElForm :model="formModel" :rules="rules" ref="formRef">
        <CustomizeFormItem label="备案人" prop="filingPerson">
          <sySelect
            ref="selectRef"
            class="w-full selectFilingPerson"
            v-model="formModel.filingPerson"
            multiple
            placeholder="请选择备案人"
          >
            <syOption
              v-for="filingPerson in filingPersonList"
              :key="filingPerson.authentication_id"
              :label="filingPerson.authentication_name"
              :value="filingPerson.authentication_id"
            >
              <div class="">
                {{ filingPerson.authentication_name }}
              </div>
            </syOption>
            <syOption :value="-2">
              <div
                @click.stop="handleClickAddFilingPersn"
                style="color: var(--sy-blue)"
                class="flex items-center"
              >
                <Icon iconName="icontianjialiucheng" class="mr-1"></Icon>
                添加备案人
              </div>
            </syOption>
          </sySelect>
        </CustomizeFormItem>
        <CustomizeFormItem label="作品名称" prop="titleOfWork">
          <syDialogInput
            v-model:value="formModel.titleOfWork"
            class="w-full"
            placeholder="请输入作品名称"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem label="作品类型" prop="typeOfWork">
          <ElRadioGroup v-model="formModel.typeOfWork">
            <syRadio label="WRITING">文字</syRadio>
            <syRadio label="MUSIC">音乐</syRadio>
            <syRadio label="PHOTOGRAPHY">摄影</syRadio>
            <syRadio label="ARTS">美术</syRadio>
            <syRadio label="FILM">视觉作品</syRadio>
            <syRadio label="OTHER">其他</syRadio>
          </ElRadioGroup>
        </CustomizeFormItem>
        <CustomizeFormItem label="创作类型" prop="typeOfCreation">
          <ElRadioGroup v-model="formModel.typeOfCreation">
            <syRadio label="ORIGINAL">原创</syRadio>
            <syRadio label="ADAPT">改编</syRadio>
            <syRadio label="TRANSLATE">翻译</syRadio>
            <syRadio label="NOTES">注释</syRadio>
            <syRadio label="ARRANGEMENT">整理</syRadio>
            <syRadio label="OTHER">其他</syRadio>
          </ElRadioGroup>
        </CustomizeFormItem>
        <CustomizeFormItem label="创作/制作完成日期" prop="dateOfCreation">
          <ElDatePicker
            class="datePicker"
            v-model="formModel.dateOfCreation"
            type="date"
            :clearable="false"
            placeholder="请选择日期"
          ></ElDatePicker>
        </CustomizeFormItem>
        <CustomizeFormItem label="创作/制作完成地点" prop="AddrOfCreation">
          <syDialogInput
            v-model:value="formModel.AddrOfCreation"
            class="w-full"
            placeholder="请输入创作/制作完成地点"
          ></syDialogInput
        ></CustomizeFormItem>
        <CustomizeFormItem label="发表状态" prop="postStatus">
          <syRadio :label="true" v-model="formModel.postStatus">已发表</syRadio>
          <syRadio :label="false" v-model="formModel.postStatus"
            >未发表</syRadio
          ></CustomizeFormItem
        >
        <CustomizeFormItem
          label="首次发表时间"
          prop="record_work_publish_date"
          v-if="formModel.postStatus"
        >
          <ElDatePicker
            class="datePicker"
            v-model="formModel.record_work_publish_date"
            type="date"
            :clearable="false"
            placeholder="请选择日期"
          ></ElDatePicker>
        </CustomizeFormItem>
        <CustomizeFormItem
          label="首次发表国家"
          prop="record_work_publish_country"
          v-if="formModel.postStatus"
        >
          <syDialogInput
            style="width: 100%"
            v-model:value="formModel.record_work_publish_country"
            placeholder="请输入首次发表国家"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          label="首次发表城市"
          prop="publish_city"
          v-if="formModel.postStatus"
        >
          <ElCascader
            popper-class="fuckCascader"
            class="w-full ElCascader"
            v-model="formModel.publish_city"
            :options="cityList"
          ></ElCascader>
        </CustomizeFormItem>
        <CustomizeFormItem label="权利取得方式" prop="wayOfObtainingPower">
          <ElRadioGroup v-model="formModel.wayOfObtainingPower">
            <syRadio label="ORIGINAL">原始</syRadio>
            <syRadio label="INHERIT">继承</syRadio>
            <syRadio label="BEAR">承受</syRadio>
            <syRadio label="OTHER">其他</syRadio>
          </ElRadioGroup>
        </CustomizeFormItem>
        <CustomizeFormItem label="其他备注说明" prop="remark">
          <syDialogInput
            v-model:value="formModel.remark"
            class="w-full"
            type="textarea"
            placeholder="请输入其他备注说明"
            rows="4"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem label="作品附件" prop="workAttachment">
          <UploadAttachment
            v-model="formModel.workAttachment"
          ></UploadAttachment>
          <div style="font-size: 14px; font-weight: 400; color: #353535">
            附件上传温馨提醒：允许上传格式： 图片: "png", "jpg", "jpeg", "gif"
            文件: "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt"
            音频: "mp3", "wma", "wav", "amr", "m4a" 视频: "wmv", "asf", "asx",
            "rm", "rmvb", "mpg", "mpeg", "mp4", "3gp", "mov", "m4v", "avi",
            "mkv", "flv", "vob"
          </div>
        </CustomizeFormItem>
      </ElForm>
      <el-checkbox
        color="var(--sy-blue)"
        v-model="formModel.agreeToTheFilingStatement"
        label="我同意备案申明"
        @select="(v) => {}"
      />
      <div style="margin-top: 31px">
        <syButton
          mode="elementBtn"
          style="width: 113px"
          type="primary"
          :loading="loading1"
          size="large"
          :disabled="!formModel.agreeToTheFilingStatement"
          @click="handleSubmit"
          >提交版权</syButton
        >
        <syButton
          mode="elementBtn"
          style="width: 113px"
          :loading="loading2"
          size="large"
          @click="handleClickSave"
          >保存草稿箱</syButton
        >
      </div>
      <div
        style="font-size: 14px; font-weight: 400; color: #353535"
        class="mt-[35px]"
      >
        <div>收费说明：</div>
        <div>
          本次申请将收取总费用
          <span style="color: #ff6268">333积分（30元）</span>
        </div>
        <div>
          其中作品备案费<span style="color: #ff6268">333积分（30元）</span>
          ,文件存储费 <span style="color: #ff6268">0积分</span>
        </div>
        <div>备案申明：</div>
        <div>
          我为上述作品的申请人,拥有上述作品根据《中华人民共和国著作权法》所规定的权利,我保证以上作品及其内容绝不违反现行有关法律、法规的相关规定。如有不实或发现有侵犯他人著作权的行为,我承担由此引起的一切法律责任。特此声明。
        </div>
      </div>
    </ModuleContainer>
  </div>
</template>

<script setup lang="ts">
import cityList from "@/config/city";
import {
  syHeaderNavBar,
  syRadio,
  sySelect,
  syOption,
  syDialogInput,
  syButton,
  formatTime,
} from "cqk-sy-ui";
import ModuleContainer from "@/components/ModuleContainer/index.vue";
import {
  ElForm,
  ElDatePicker,
  ElCheckbox,
  ElCascader,
  ElRadioGroup,
  ElMessage,
} from "element-plus";
import { nextTick, onMounted, ref, watch } from "vue";
import Icon from "@/components/Icon/index.vue";
import CustomizeFormItem from "@/components/Form/CustomizeFormItem.vue";
import UploadAttachment from "./components/UploadAttachment/index.vue";
import AddFilingPerson from "../AddFilingPerson/index.vue";
import {
  getAuths,
  getCopyRight,
  postCopyRight,
} from "@/service/copyrightService";
import { eStatusOfFilerCertification } from "@/components/ApproveStatus/status";
import { iAuth, iCopyRight, iCopyrightPostData } from "@/types/copyright";
import { router } from "@/router";
import { useRoute } from "vue-router";
const formRef = ref<InstanceType<typeof ElForm>>();
const loading1 = ref(false);
const loading2 = ref(false);
const addFilingPersonVisible = ref(false);

const formModel = ref({
  filingPerson: [] as number[],
  titleOfWork: "",
  typeOfWork: "",
  typeOfCreation: "",
  dateOfCreation: undefined as undefined | string,
  AddrOfCreation: "",
  postStatus: false,
  record_work_publish_date: "",
  wayOfObtainingPower: "",
  record_work_publish_country: "",
  publish_city: [] as string[],
  remark: "",
  workAttachment: undefined as any,
  agreeToTheFilingStatement: false,
});
const rules = ref({
  filingPerson: [{ required: true, message: "请选择备案人" }],
  titleOfWork: [{ required: true, message: "请输入作品名称" }],
  typeOfWork: [{ required: true, message: "请选择作品类型" }],
  typeOfCreation: [{ required: true, message: "请输入创作类型" }],
  dateOfCreation: [{ required: true, message: "请选择日期" }],
  AddrOfCreation: [{ required: true, message: "请输入创作/制作完成地点" }],
  postStatus: [{ required: true, message: "请选择发表状态" }],
  wayOfObtainingPower: [{ required: true, message: "请选择权利取得方式" }],
  record_work_publish_date: [{ required: true, message: "请选择首次发表日期" }],
  publish_city: [{ required: true, message: "请选择首次发表城市" }],
  record_work_publish_country: [
    { required: true, message: "请输入首次发表国家" },
  ],
  remark: [],
  workAttachment: [{ required: true, message: "请上传文件" }],
  agreeToTheFilingStatement: [],
});

const selectRef = ref();

onMounted(async () => {
  const route = useRoute();
  if (route.query.id) {
    const res = await getCopyRight(Number(route.query.id));
    if (res?.code === 200) {
      const data = res?.data as iCopyRight;
      formModel.value.filingPerson = data.authentication_ids;
      formModel.value.titleOfWork = data.record_work_name;
      formModel.value.typeOfWork = data.record_work_type;
      formModel.value.typeOfCreation = data.record_work_nature;
      formModel.value.dateOfCreation! = data.record_work_finish_date;
      formModel.value.AddrOfCreation = data.record_work_finish_address;
      formModel.value.postStatus = data.record_work_publish_state;
      formModel.value.wayOfObtainingPower = data.record_work_gain_source;
      formModel.value.remark = data.record_work_description;
      formModel.value.workAttachment = {
        ...data.record_work_attachment,
        name: data.record_work_attachment.url.slice(
          data.record_work_attachment.url.lastIndexOf("/") + 1
        ),
      };
      if (formModel.value.postStatus) {
        formModel.value.record_work_publish_date =
          data.record_work_publish_date;
        formModel.value.record_work_publish_country =
          data.record_work_publish_country;
        formModel.value.publish_city = [
          data.record_work_publish_province,
          data.record_work_publish_city,
        ];
      }
    }
  }
});

function replace() {
  const text = document.querySelector(
    ".selectFilingPerson .el-select__tags-text"
  );
  if (text) {
    if (
      text.innerHTML.indexOf(
        '<span style="color: var(--sy-blue)">(主备案人)</span>'
      ) == -1
    ) {
      text.innerHTML =
        text.innerHTML +
        `&nbsp<span style="color: var(--sy-blue)">(主备案人)</span>`;
    }
  }
}

watch(
  () => formModel.value.filingPerson,
  (newV) => {
    nextTick(() => {
      replace();
    });
  }
);

function handleClickAddFilingPersn() {
  selectRef.value.blur();
  addFilingPersonVisible.value = true;
}

const getParams = ({ to_drafts }: { to_drafts: boolean }) => {
  const { raw, status, uid, ...workAttachment } =
    formModel.value.workAttachment || {};
  let params = {
    record_work_name: formModel.value.titleOfWork,
    record_work_type: formModel.value.typeOfWork,
    record_work_nature: formModel.value.typeOfCreation,
    record_work_finish_date: formatTime(
      new Date(formModel.value.dateOfCreation!).getTime(),
      "YYYY-MM-DD"
    ),
    record_work_finish_address: formModel.value.AddrOfCreation,
    record_work_publish_state: formModel.value.postStatus,
    record_work_gain_source: formModel.value.wayOfObtainingPower,
    record_work_description: formModel.value.remark,
    record_work_attachment: workAttachment,
    authentication_ids: formModel.value.filingPerson,
    contact_person: filingPersonList.value.find(
      (i) => i.authentication_id === formModel.value.filingPerson[0]
    )?.contact_person,
    contact_email: filingPersonList.value.find(
      (i) => i.authentication_id === formModel.value.filingPerson[0]
    )?.contact_email,
    contact_telephone: filingPersonList.value.find(
      (i) => i.authentication_id === formModel.value.filingPerson[0]
    )?.contact_telephone,
    contact_post_code: filingPersonList.value.find(
      (i) => i.authentication_id === formModel.value.filingPerson[0]
    )?.contact_post_code,
    contact_fax: filingPersonList.value.find(
      (i) => i.authentication_id === formModel.value.filingPerson[0]
    )?.contact_fax,
    contact_address: filingPersonList.value.find(
      (i) => i.authentication_id === formModel.value.filingPerson[0]
    )?.contact_address,
    authentication_main_id: formModel.value.filingPerson[0],
    contact_mobile: filingPersonList.value.find(
      (i) => i.authentication_id === formModel.value.filingPerson[0]
    )?.contact_mobile,
    to_drafts: to_drafts,
  } as iCopyrightPostData;
  if (params.record_work_publish_state === true) {
    params = {
      ...params,
      record_work_publish_date: formatTime(
        new Date(formModel.value.record_work_publish_date),
        "YYYY-MM-DD"
      ),
      record_work_publish_country: formModel.value.record_work_publish_country,
      record_work_publish_province: formModel.value.publish_city[0],
      record_work_publish_city: formModel.value.publish_city[1],
    };
  }
  return params;
};

const handleClickSave = async () => {
  loading2.value = true;
  formRef.value?.validate(async (isValid) => {
    console.log(isValid, "isValid");
    if (isValid) {
      const params = getParams({
        to_drafts: true,
      });
      const res = await postCopyRight(params);
      if (res && res.code === 200) {
        ElMessage.success("保存成功");
        router.push({
          name: "draftBox",
        });
      }
    }
  });
  loading2.value = false;
};

const handleSubmit = () => {
  loading1.value = true;
  formRef.value?.validate(async (isValid) => {
    if (isValid) {
      const params = getParams({
        to_drafts: false,
      });
      const res = await postCopyRight(params);
      loading1.value = false;
      if (res && res.code === 200) {
        ElMessage.success("添加成功");
        router.push({
          name: "copyrightManagement",
        });
      } else {
        res?.msg && ElMessage.error(res.msg);
      }
    }
  });
};

const filingPersonList = ref<iAuth[]>([]);

onMounted(() => {
  getAuths(
    "",
    [
      eStatusOfFilerCertification.PASSED,
      eStatusOfFilerCertification.WAITING_CHECK,
    ],
    1,
    200
  ).then((res) => {
    if (res && res.code === 200) {
      filingPersonList.value = res.data.results;
      nextTick(() => {
        replace();
      });
    }
  });
});
</script>

<style lang="scss" scoped>
.addCopyRight {
  .title {
    font-size: 30px;
    font-weight: 600;
    color: #191919;
    line-height: 42px;
  }
  .tip {
    font-size: 14px;
    font-weight: 400;
    color: #ababab;
  }
}
:deep(.ElCascader) {
  .el-input__inner {
    padding-left: 18px !important;
    border-radius: 8px;
    height: 36px;
    line-height: 36px;
  }
}
</style>
