<template>
  <div>
    <a-button @click="showModal" type="primary">我要发榜</a-button>
    <a-modal :confirm-loading="confirmLoading" :title="title" :visible="visible" @cancel="handleCancel" @ok="handleOk" width="50%">
      <a-form :form="form">
        <!-- 需求名称 -->
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" class="mb-3" label="需求名称">
          <a-input placeholder="请输入需求名称..." v-model.trim="platform.needName" />
        </a-form-item>
        <!-- 技术领域 -->
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" class="mb-3" label="技术领域">
          <a-input placeholder="请输入技术领域..." v-model.trim="platform.technicalField" />
        </a-form-item>
        <!-- 需求截止时间 -->
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" class="mb-3" label="需求截止时间">
          <a-date-picker @change="changeNeedTime" style="width: 100%" />
        </a-form-item>
        <!-- 需求类别 -->
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" class="mb-3" label="需求类别">
          <a-checkbox-group @change="onChange" class="line-height-30">
            <a-checkbox v-for="(item, index) in typeList" :key="index" :value="item.id">{{ item.name }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <!-- 需求内容 -->
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" class="mb-3" label="需求内容">
          <quill-editor
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @change="onEditorChange($event)"
            @focus="onEditorFocus($event)"
            class="editor-box"
            ref="myQuillEditor"
            v-model="needContent"
          ></quill-editor>
          <a-upload
            accept="image/png, image/jpeg"
            name="files"
            :multiple="false"
            style="display: none"
            :action="action"
            @change="fileChange"
          >
            <a-button id="upload-img"> <a-icon type="upload" /></a-button>
          </a-upload>
        </a-form-item>
        <!-- 现有基础 -->
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" class="mb-3" label="现有基础">
          <a-textarea
            placeholder="（已经开展的工作、所处阶段、投入资金和人力、仪器 设备、生产条件等）"
            style="min-height: 100px"
            v-model.trim="platform.basics"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal :confirm-loading="confirmLoading1" title="需要登录" :visible="visible1" @cancel="handleCancel1" @ok="handleOk1" width="50%">
      还没有登录，请您先去登录 <span style="color: rgba(0, 0, 0, 0.65)"> （点击确定前往登录）</span>
    </a-modal>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import { quillEditor } from 'vue-quill-editor'; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { upload, addTelease, findTypeList } from 'config/api';

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};
const formTailLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18, offset: 6 },
};
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
  ['blockquote', 'code-block'], //引用，代码块
  [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
  [{ list: 'ordered' }, { list: 'bullet' }], //列表
  [{ script: 'sub' }, { script: 'super' }], // 上下标
  [{ indent: '-1' }, { indent: '+1' }], // 缩进
  [{ direction: 'rtl' }], // 文本方向
  // [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
  // [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
  [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
  // [{ font: [] }], //字体
  [{ align: [] }], //对齐方式
  ['clean'], //清除字体样式
  ['image', 'video'], //上传图片、上传视频
];

export default {
  name: 'Enroll',
  components: { quillEditor },
  data() {
    return {
      form: this.$form.createForm(this, { name: 'submit' }),
      visible: false,
      visible1: false,
      title: '发榜',
      action: upload,
      formItemLayout,
      formTailLayout,
      confirmLoading: false,
      confirmLoading1: false,
      needContent: ``,
      editorOption: {
        placeholder: '在这里输入...',
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function(value) {
                if (value) {
                  // alert('自定义图片');
                  document.getElementById('upload-img').click();
                } else {
                  this.quill.format('image', false);
                }
              },
              video: function(value) {
                if (value) {
                  alert('自定义视频');
                } else {
                  this.quill.format('image', false);
                }
              },
            },
          },
        },
      },
      platform: {
        needName: '',
        technicalField: '',
        basics: '',
        type: [],
        buildTime: '',
      },
      hideMessage: null,
      typeList: [],
    };
  },
  computed: mapState('user', ['anyringToken']),
  created() {
    this.findType();
  },
  methods: {
    // 需求截止时间
    changeNeedTime(date, dateString) {
      this.platform.buildTime = this.$moment(date).format('YYYY-MM-DD HH:mm:ss');
      // console.log(this.$moment(date).unix(), dateString);
    },

    onEditorReady(editor) {
      // 准备编辑器
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {
      // 内容改变事件
      // console.log(this.content);
    },
    onChange(e) {
      console.log(e);
      this.platform.type = e;
    },
    // 上传图片事件
    fileChange(info) {
      console.log(info);
      if (info.file.status === 'uploading') {
        if (!this.hideMessage) {
          this.hideMessage = this.$message.loading('上传中...');
        }
      }
      // this.fileList = info.fileList;
      if (info.file.status === 'done') {
        this.files = [];
        const img = `<img src=${info.file.response.data[0].visitUrl} >`;
        this.needContent += img;
        setTimeout(this.hideMessage, 0);
        this.$message.success('上传成功');
      }
    },

    // 显示表单输入框
    showModal() {
      if (this.anyringToken) {
        this.visible = true;
      } else {
        this.visible1 = true;
      }
    },
    // 取消显示
    handleCancel(e) {
      this.visible = false;
    },
    // 点击确定
    handleOk() {
      this.subMitAdd();
    },
    handleCancel1() {
      this.visible1 = false;
    },
    // 点击确定
    handleOk1() {
      this.$router.push('/login');
    },
    // 加入接口
    async subMitAdd() {
      this.confirmLoading = true;
      try {
        const params = {
          param: {
            title: this.platform.needName,
            content: this.needContent,
            servics: this.platform.technicalField,
            deadline: this.platform.buildTime,
            existingBasis: this.platform.basics,
            models: this.platform.type,
          },
        };
        const res = await addTelease(params);
        const { code, msg, data } = res.data;
        if (code === 200) {
          this.$message.success('发榜成功');
          this.visible = false;
          this.confirmLoading = false;
          for (let key in this.platform) {
            this.platform[key] = '';
          }
        } else {
          throw msg;
          this.confirmLoading = false;
        }
      } catch (error) {
        this.$message.error(error);
        this.confirmLoading = false;
      }
    },

    // 查询分类列表
    async findType() {
      try {
        const res = await findTypeList();
        const { code, msg, data } = res.data;
        if (code === 200) {
          this.typeList = data;
        } else {
          console.log(msg);
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style lang="stylus" scoped>
.must-color {
  color: red;
}

.code_img {
  height: 32px;
  width: 120px;
}

.ql-editor {
  min-height: 600px;
  max-height: 800px;
}

.editor-box >>> .ql-editor {
  min-height: 150px;
}
</style>
