<template>
  <div class="d-flex flex-wrap pb-3">
    <!-- 编辑 -->
    <a-modal
      :maskClosable="false"
      @cancel="$emit('closeModal')"
      destroyOnClose
      footer
      title="修改成果"
      v-model="editVisible"
      width="700px"
    >
      <a-form :form="form" @submit="handleSubmit" v-if="editVisible && editItem && editItem.info">
        <!-- 成果名称 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="成果名称"
        >
          <a-input
            placeholder="请输入成果名称"
            v-decorator="[
                      'name',
                      {
                        initialValue: editItem.info.name,
                        rules: [
                          { required: true, message: '成果名称不能为空' },
                          { whitespace: true, message: '成果名称不能为空' },
                          { max: 140, massage: '成果名称最多140个字符' },
                        ],
                      },
                    ]"
          />
        </a-form-item>
        <!-- 成果水平 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="成果水平"
        >
          <a-select
            placeholder="请选择成果水平"
            style="width:100%"
            v-decorator="[
                      'level',{initialValue: editItem.info.level}
                    ]"
          >
            <a-select-option :key="type.id" :value="type.id" v-for="type in levels">{{ type.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 成果范围 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="成果范围"
        >
          <a-select
            placeholder="请选择成果范围"
            style="width:100%"
            v-decorator="[
                      'ranges',{initialValue: editItem.info.ranges}
                    ]"
          >
            <a-select-option
              :key="type.id"
              :value="type.id"
              v-for="type in assignments"
            >{{ type.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 成果阶段 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="成果阶段"
        >
          <a-select
            placeholder="请选择成果阶段"
            style="width:100%"
            v-decorator="[
                      'stage',{initialValue: editItem.info.stage}
                    ]"
          >
            <a-select-option :key="type.id" :value="type.id" v-for="type in stages">{{ type.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 成果表现形式 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="成果表现形式"
        >
          <a-select
            placeholder="请选择成果表现形式"
            style="width:100%"
            v-decorator="[
                      'performance',{initialValue: editItem.info.performance}
                    ]"
          >
            <a-select-option
              :key="type.id"
              :value="type.id"
              v-for="type in performances"
            >{{ type.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 成果标准 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="成果标准"
        >
          <a-select
            placeholder="请选择成果标准"
            style="width:100%"
            v-decorator="[
                      'standard',{initialValue: editItem.info.standard}
                    ]"
          >
            <a-select-option
              :key="type.id"
              :value="type.id"
              v-for="type in standards"
            >{{ type.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 申请人 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="申请人"
        >
          <a-input
            placeholder="请输入申请人"
            v-decorator="[
                      'applicant',{initialValue: editItem.info.applicant}
                    ]"
          />
        </a-form-item>
        <!-- 已转让企业数 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="已转让企业数"
        >
          <a-input
            placeholder="请输入已转让企业数"
            v-decorator="[
                      'assignment',{initialValue: editItem.info.assignment}
                    ]"
          />
        </a-form-item>
        <!-- 学科分类 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="学科分类"
        >
          <a-input
            placeholder="请输入学科分类"
            v-decorator="[
                      'classification',{initialValue: editItem.info.classification}
                    ]"
          />
        </a-form-item>
        <!-- 所属领域 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="所属领域"
        >
          <a-checkbox-group
            @change="onChange($event,'domains','domain')"
            v-decorator="[
                      'domain',{initialValue: oldDomain}
                    ]"
          >
            <a-checkbox
              :disabled="item.disabled"
              :key="item.id"
              :value="item.id"
              class="my-2"
              v-for="item in domains"
            >{{ item.value }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <!-- 知识产权 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="知识产权"
        >
          <a-select
            placeholder="请选择知识产权"
            style="width:100%"
            v-decorator="[
                      'finance',{initialValue: editItem.info.finance}
                    ]"
          >
            <a-select-option
              :key="type.id"
              :value="type.id"
              v-for="type in finances"
            >{{ type.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 编号 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="编号"
        >
          <a-input
            placeholder="请输入编号"
            v-decorator="[
                      'identifier',{initialValue: editItem.info.identifier}
                    ]"
          />
        </a-form-item>
        <!-- 转让收入 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="转让收入（万元）"
        >
          <a-input
            placeholder="请输入转让收入（万元）"
            v-decorator="[
                      'income',{initialValue: editItem.info.income}
                    ]"
          />
        </a-form-item>
        <!-- 发明人 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="发明人"
        >
          <a-input
            placeholder="请输入发明人"
            v-decorator="[
                      'inventor',{initialValue: editItem.info.inventor}
                    ]"
          />
        </a-form-item>
        <!-- 关键词 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="关键词"
        >
          <div class="d-flex flex-nowrap">
            <a-input
              class="mr-2"
              placeholder="关键词1"
              v-decorator="[
                      'keywordone',{initialValue: editItem.info.keywordone}
                    ]"
            />
            <a-input
              class="mr-2"
              placeholder="关键词2"
              v-decorator="[
                      'keywordtwo',{initialValue: editItem.info.keywordtwo}
                    ]"
            />
            <a-input
              placeholder="关键词3"
              v-decorator="[
                      'keywordthree',{initialValue: editItem.info.keywordthree}
                    ]"
            />
          </div>
        </a-form-item>
        <!-- 转让形式 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="转让形式"
        >
          <a-select
            placeholder="请选择转让形式"
            style="width:100%"
            v-decorator="[
                      'layout',{initialValue: editItem.info.layout}
                    ]"
          >
            <a-select-option
              :key="type.id"
              :value="type.id"
              v-for="type in layouts"
            >{{ type.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 类型 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="类型"
        >
          <a-checkbox-group
            v-decorator="[
                      'modelIds',
                      {
                        initialValue: oldTypes ? oldTypes : [],
                        rules: [
                          { required: true, message: '类型不能为空' },
                        ],
                      },
                    ]"
          >
            <a-checkbox :key="item.id" :value="item.id" v-for="item in typeLists">{{ item.name }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <!-- 专利数 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="专利数"
        >
          <a-input
            placeholder="请输入专利数"
            v-decorator="[
                      'nums',{initialValue: editItem.info.nums}
                    ]"
          />
        </a-form-item>
        <!-- 专利情况 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="专利情况"
        >
          <a-select
            placeholder="请选择专利情况"
            style="width:100%"
            v-decorator="[
                      'patent',{initialValue: editItem.info.patent}
                    ]"
          >
            <a-select-option
              :key="type.id"
              :value="type.id"
              v-for="type in patents"
            >{{ type.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 图片 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="图片"
          required
        >
          <a-upload
            :action="upload"
            :before-upload="beforeUpload"
            @change="handleChange"
            list-type="picture"
            name="files"
          >
            <a-button v-show="fileList.length - 0 === 0">
              <a-icon type="upload" />选择图片
            </a-button>
          </a-upload>
        </a-form-item>
        <!-- 未应用原因 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="未应用原因"
        >
          <a-checkbox-group
            @change="onChange($event,'reasons','reason')"
            v-decorator="[
                      'reason',{initialValue: oldReason}
                    ]"
          >
            <a-checkbox
              :disabled="item.disabled"
              :key="item.id"
              :value="item.id"
              class="my-2"
              v-for="item in reasons"
            >{{ item.value }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <!-- 专利名称 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="专利名称"
        >
          <a-input
            placeholder="请输入专利名称"
            v-decorator="[
                      'registerName',{initialValue: editItem.info.registerName}
                    ]"
          />
        </a-form-item>
        <!-- 专利号 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="专利号"
        >
          <a-input
            placeholder="请输入专利号"
            v-decorator="[
                      'registerNum',{initialValue: editItem.info.registerNum}
                    ]"
          />
        </a-form-item>
        <!-- 所属单位 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="所属单位"
        >
          <a-select
            placeholder="请选择所属单位"
            style="width:100%"
            v-decorator="[
                      'research',{initialValue: editItem.info.research}
                    ]"
          >
            <a-select-option
              :key="index"
              :value="type.id"
              v-for="(type, index) in types"
            >{{ type.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 研究形式 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="研究形式"
        >
          <a-select
            placeholder="请选择研究形式"
            style="width:100%"
            v-decorator="[
                      'shape',{initialValue: editItem.info.shape}
                    ]"
          >
            <a-select-option :key="type.id" :value="type.id" v-for="type in shapes">{{ type.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 应用状态 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="应用状态"
        >
          <a-select
            placeholder="请选择应用状态"
            style="width:100%"
            v-decorator="[
                      'situation',{initialValue: editItem.info.situation}
                    ]"
          >
            <a-select-option
              :key="type.id"
              :value="type.id"
              v-for="type in situations"
            >{{ type.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 专利类型 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="专利类型"
        >
          <a-input
            placeholder="请输入专利类型"
            v-decorator="[
                      'style',{initialValue: editItem.info.style}
                    ]"
          />
        </a-form-item>
        <!-- 简介 -->
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="简介"
          required
        >
          <quill-editor
            :max-size="maxSize"
            :placeholder="placeholder"
            :value="editItem.info.content"
            @changeInput="changeInput"
          />
        </a-form-item>

        <a-form-item class="d-flex flex-row-reverse">
          <a-button @click="$emit('closeModal')" class="mr-3">取消</a-button>
          <a-button class="white--text" html-type="submit" type="primary">保存</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { upload, selResUpdate } from 'config/api';
import { mapActions } from 'vuex';
import QuillEditor from 'components/QuillEditor/QuillEditor.vue';
import addMixin from './mixins/addMixin.js';

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const tailItemLayout = { wrapperCol: { span: 16, offset: 6 } };

export default {
  name: 'DevelopmentEdit',
  props: {
    editVisible: { type: Boolean, default: false },
    editItem: { type: Object, default: () => {} },
    typeLists: { type: Array, default: () => [] },
  },
  components: { QuillEditor },
  mixins: [addMixin],
  data() {
    return {
      formItemLayout,
      tailItemLayout,
      form: this.$form.createForm(this, { name: 'development-edit' }),
      upload: upload,
      fileList: [],
      //限制文件上传的格式和大小
      beforeUpload: file => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          this.$message.error('仅支持 JPG/PNG 格式的图片!');
        }
        return isJpgOrPng;
      },
      types: [],
      maxSize: 2048,
      content: '',
      placeholder: '请输入...',
      domain: [], // 所属领域
      reason: [], // 未应用原因
    };
  },

  computed: {
    oldTypes() {
      const { typeLists, editItem } = this;
      let arr = [];
      for (let i = 0; i < typeLists.length; i++) {
        const item = typeLists[i];
        const a = editItem.info.names.findIndex(a => a === item.name);
        const index = arr.findIndex(c => c === a);
        if (a !== -1 && index === -1) {
          arr.push(item.id);
        }
      }
      return arr;
    },

    oldDomain() {
      let { domains, editItem } = this;
      let arr = [];
      for (let i = 0; i < domains.length; i++) {
        const item = domains[i];
        if (editItem.info.domainone && item.value === editItem.info.domainone) {
          arr.push(item.id);
        }
        if (editItem.info.domaintwo && item.value === editItem.info.domaintwo) {
          arr.push(item.id);
        }

        if (editItem.info.domainone && editItem.info.domaintwo) {
          item.disabled = true;
          const a = domains.find(a => a.value === editItem.info.domainone);
          a.disabled = false;
          const b = domains.find(b => b.value === editItem.info.domaintwo);
          b.disabled = false;
        }
      }
      this.domain = arr;
      return arr;
    },

    oldReason() {
      let { reasons, editItem } = this;
      let arr = [];
      for (let i = 0; i < reasons.length; i++) {
        const item = reasons[i];
        if (editItem.info.reansonone && item.value === editItem.info.reansonone) {
          arr.push(item.id);
        }
        if (editItem.info.reansontwo && item.value === editItem.info.reansontwo) {
          arr.push(item.id);
        }

        if (editItem.info.reansonone && editItem.info.reansontwo) {
          item.disabled = true;
          const a = reasons.find(a => a.value === editItem.info.reansonone);
          a.disabled = false;
          const b = reasons.find(b => b.value === editItem.info.reansontwo);
          b.disabled = false;
        }
      }
      this.reason = arr;
      return arr;
    },
  },

  async created() {
    const params = {
      param: {
        pageNum: 1,
        pageSize: 10,
        model: 2,
      },
    };
    this.types = await this.getSelModelSearch(params);
  },

  methods: {
    ...mapActions(['getSelModelSearch']),

    // 多选最多两项（所属领域、未应用原因）
    onChange(checkedValues, arr, type) {
      this[type] = checkedValues;
      this[arr][checkedValues[0]].disabled = false;
      if (checkedValues.length < 2) {
        for (let i = 0; i < this[arr].length; i++) {
          const item = this[arr][i];
          item.disabled = false;
        }
      }
      if (checkedValues.length > 1) {
        for (let i = 0; i < this[arr].length; i++) {
          const item = this[arr][i];
          item.disabled = true;
          for (let j = 0; j < checkedValues.length; j++) {
            const element = checkedValues[j];
            if (item.id === element) {
              item.disabled = false;
            }
          }
        }
      }
    },

    // 上传图片
    handleChange(info) {
      if (info.file.status === 'done') {
        this.fileList.push(info.file.response.data[0].id);
      } else if (info.file.status === 'removed') {
        this.fileList = info.fileList;
      }
    },

    // 修改内容
    changeInput(value) {
      this.content = value;
    },

    // 提交表单
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFieldsAndScroll(async (err, values) => {
        if (!err) {
          try {
            const params = this.generateSaveParams(values);
            const res = await selResUpdate(params);
            const { data, msg, code } = res.data;
            if (code === 200) {
              this.$message.success('修改成功');
              this.$emit('selResSearch');
            } else {
              throw msg;
            }
            this.$emit('closeModal');
          } catch (error) {
            this.$message.error(error || '修改成果失败');
            this.$emit('closeModal');
          }
        }
      });
    },

    // 验证提交信息
    generateSaveParams(values) {
      const { performance, standard, stage, level, ranges, shape, finance, patent, situation, layout } = values;
      const params = { param: values };
      const { fileList, domain, reason, content, editItem } = this;
      params.param.id = editItem.id;
      params.param.pic = fileList[0] ? fileList[0] : editItem.info.picId;
      params.param.content = content ? content : editItem.info.content;
      params.param.domainone = domain && domain.length > 0 && domain[0] ? domain[0] : editItem.info.domainone;
      params.param.domaintwo = domain && domain.length > 1 && domain[1] ? domain[1] : editItem.info.domaintwo;
      params.param.reansonone = reason && reason.length > 0 && reason[0] ? reason[0] : editItem.info.reansonone;
      params.param.reansontwo = reason && reason.length > 1 && reason[1] ? reason[1] : editItem.info.reansontwo;
      if (!this.isNumber(performance)) {
        params.param.performance = '';
      }
      if (!this.isNumber(standard)) {
        params.param.standard = '';
      }
      if (!this.isNumber(stage)) {
        params.param.stage = '';
      }
      if (!this.isNumber(level)) {
        params.param.level = '';
      }
      if (!this.isNumber(ranges)) {
        params.param.ranges = '';
      }
      if (!this.isNumber(shape)) {
        params.param.shape = '';
      }
      if (!this.isNumber(finance)) {
        params.param.finance = '';
      }
      if (!this.isNumber(patent)) {
        params.param.patent = '';
      }
      if (!this.isNumber(situation)) {
        params.param.situation = '';
      }
      if (!this.isNumber(layout)) {
        params.param.layout = '';
      }
      return params;
    },

    // 是否是数字
    isNumber(val) {
      var regPos = /^\d+(\.\d+)?$/; //非负浮点数
      var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
      if (regPos.test(val) || regNeg.test(val)) {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>

<style scoped lang="stylus">
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
