<template>
  <div>
    <el-card shadow="hover" class="mgb20">
      <div class="flex-between">
        <div class="per_title" v-preventReClick @click="back">
          <i class="el-icon-arrow-left"></i>
          <span class="per_back">返回</span>
          <span class="per_school" v-text="form.id ? '编辑方案' : '新建方案'"></span>
        </div>
      </div>
    </el-card>
    <div class="page">
      <el-form :model="form" :rules="rules" class="input-form model" label-width="140px">
        <div class="item-line">
          <el-form-item prop="title" label="标题">
            <el-input placeholder="请输入标题" v-model.trim="form.title" clearable maxlength="30"
              class="inline-input"></el-input>
          </el-form-item>
          <el-form-item prop="classificationId" label="所属分类">
            <el-select style="width: 234px;" v-model="form.classificationId">
              <template v-for="item in classifications">
                <el-option v-if="item.id" :key="item.id" :label="item.classificationName" :value="item.id">
                </el-option>
              </template>
            </el-select>
            <el-button class="set-btn" type="primary" @click="setClass">设置</el-button>
          </el-form-item>
        </div>
        <el-form-item prop="applicableMajor" label="适用专业">
          <el-input style="width: 940px" type="textarea" v-model.trim="form.applicableMajor" :rows="3"
            clearable></el-input>
        </el-form-item>
        <el-form-item prop="schemeIntroduction" label="方案简介">
          <el-input style="width: 940px" type="textarea" v-model.trim="form.schemeIntroduction" :rows="3"
            clearable></el-input>
        </el-form-item>
        <el-form-item prop="product" label="产品">
          <el-button style="margin-bottom: 5px" type="primary" @click="showProduct">请选择</el-button>
          <div>
            <el-tag v-for="(tag, i) in form.productList" :key="i" class="tag" closable @close="delCheckedProduct(i)">
              {{ tag.productName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item prop="schemeFile" label="方案文件">
          <Upload :max-size="100000" :file-list.sync="fileList" :on-remove="handleRemove"
            @onSuccess="uploadSuccessFile" />
        </el-form-item>
      </el-form>
      <div class="btns">
        <el-button type="primary" @click="submit(1)">发布</el-button>
        <el-button @click="submit(0)">保存草稿</el-button>
        <el-button @click="back">取消</el-button>
      </div>
    </div>

    <el-dialog title="所属分类设置" :visible.sync="classVisible" width="500px" :close-on-click-modal="false"
      class="manage-dia" :before-close="closeClass">
      <div class="plus">
        <i class="el-icon-circle-plus-outline" @click="addClass"></i>
      </div>
      <el-table :data="classifications" ref="table" header-align="center" row-key="id">
        <el-table-column type="index" width="60" label="序号" align="center"></el-table-column>
        <el-table-column prop="classificationName" label="分类名称" align="center" min-width="130">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit" placeholder="请输入分类名称" v-model="scope.row.classificationName" clearable
              maxlength="30"></el-input>
            <span v-else>{{ scope.row.classificationName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime1" label="是否引用" align="center" min-width="60">否</el-table-column>
        <el-table-column label="操作" align="center" min-width="60">
          <template slot-scope="scope">
            <i v-if="scope.row.edit" class="el-icon-check edit" @click="submitClass(scope.row)"></i>
            <i v-else class="el-icon-edit edit" @click="editClass(scope.row)"></i>
            <i class="el-icon-delete del" @click="delClass(scope.row, scope.$index)"></i>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button @click="closeClass">返回</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="productVisible" width="1200px" center custom-class="product-dia">
      <div class="product-wrap">
        <div class="item type">
          <div class="title-wrap flex-center">
            <p class="addhr_tag"></p>
            <span>产品分类</span>
          </div>
          <ul class="types">
            <li v-for="(item, i) in productCategories" :key="i" :class="{ active: curType == item.classificationId }"
              @click="typeClick(item)">
              {{ item.classificationName }}
            </li>
          </ul>
        </div>

        <div class="item products">
          <div class="title-wrap flex-center">
            <p class="addhr_tag"></p>
            <span>产品列表</span>
          </div>
          <el-input class="mgb10" placeholder="请输入产品名称" prefix-icon="el-icon-search" v-model.trim="keyword"
            clearable></el-input>
          <el-table :data="products" class="table" ref="table" header-align="center" max-height="470"
            @selection-change="handleSelectionChange" row-key="mallId">
            <el-table-column type="selection" width="55" align="center" :reserve-selection="true"></el-table-column>
            <el-table-column type="index" width="55" label="序号" align="center"></el-table-column>
            <el-table-column prop="productName" label="产品名称" align="center"></el-table-column>
            <el-table-column prop="supplierName" label="厂商" align="center"></el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination background layout="total, prev, pager, next" :total="total"
              @current-change="handleCurrentChange" :current-page="page">
            </el-pagination>
          </div>
        </div>

        <div class="item checked">
          <div class="title-wrap flex-center">
            <p class="addhr_tag"></p>
            <span>已选择产品（{{ checkeds.length }}个）</span>
          </div>
          <el-table :data="checkeds" class="table" header-align="center" max-height="470">
            <el-table-column type="index" width="55" label="序号" align="center"></el-table-column>
            <el-table-column prop="productName" label="产品名称" align="center"></el-table-column>
            <el-table-column prop="supplierName" label="厂商" align="center"></el-table-column>
            <el-table-column prop="typeName" label="产品类型" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="55">
              <template slot-scope="scope">
                <i :class="['el-icon-delete rm', { disabled: scope.row.disabled }]"
                  @click="delProduct(scope.$index, scope.row)"></i>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="productVisible = false">取 消</el-button>
        <el-button type="primary" @click="productSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Setting from '@/setting'
import Util from '@/libs/util'
import Editor from '@tinymce/tinymce-vue'
import editorConfig from '@/utils/editor'
import Cropper from '@/components/img-upload/Cropper'
import Upload from '@/components/upload';
import Oss from '@/components/upload/upload.js'
import Axios from 'axios'
export default {
  data () {
    return {
      headers: {
        token: sessionStorage.getItem('token')
      },
      nameRepeat: false,
      form: {
        id: this.$route.query.id || '',
        applicableMajor: '',
        classificationId: '',
        productList: [],
        fileName: '',
        schemeFile: '',
        title: '',
        schemeIntroduction: ''
      },
      fileList: [],
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        classificationId: [
          { required: true, message: '请选择所属分类', trigger: 'change' }
        ],
        applicableMajor: [
          { required: true, message: '请输入适用专业', trigger: 'blur' }
        ],
        schemeIntroduction: [
          { required: true, message: '请输入方案简介', trigger: 'blur' }
        ],
        product: [
          { required: true, message: '请输入产品', trigger: 'blur' }
        ],
        schemeFile: [
          { required: true, message: '请选择方案文件', trigger: 'change' }
        ],
      },
      editorConfig,
      submiting: false, // 新增编辑防抖标识
      pass: false,
      uploading: 0,
      updateTime: 0,
      cropperModel: false,
      isUpload: false,
      fixedNumber: [1.76, 1],
      file: {}, // 当前被选择的图片文件
      classifications: [],
      classVisible: false,
      labels: [],
      labelVisible: false,

      productVisible: false,
      productCategories: [],
      curType: 1,
      checkeds: [],
      total: 0,
      page: 1,
      pageSize: 10,
      products: [],
      multipleSelection: [],
      keyword: '',
      loading: false,
    };
  },
  components: {
    Editor,
    Cropper,
    Upload
  },
  watch: {
    // 监听信息是否有更改,有的话页面离开的时候要询问是否要保存
    form: {
      handler (val) {
        this.updateTime++
      },
      deep: true
    },
    keyword: function (val) {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.initData();
      }, 500);
    }
  },
  // 页面离开的时候如果没有保存则提示
  beforeRouteLeave (to, from, next) {
    if (this.submiting) {
      next()
    } else if (!this.pass) {
      // 更改了信息才需要提示
      if (this.updateTime) {
        this.$confirm(`所填写内容暂未保存，是否保存？`, '提示', {
          type: 'warning',
          closeOnClickModal: false
        }).then(() => {
          this.submit(this.form.isRelease, next)
        }).catch(() => {
          next()
        })
      } else {
        next()
      }
    } else {
      next()
    }
  },
  mounted () {
    this.getArticle()
  },
  methods: {
    // 详情
    getArticle () {
      const { id } = this.form
      id ? this.$post(`${this.api.findByIdScheme}?id=${id}`).then(({ data }) => {
        if (data.schemeFile) this.fileList = [{ name: data.fileName, url: data.schemeFile }]
        if (!data.productList) data.productList = []
        this.form = data
        this.getClassification(1)
      }).catch(err => { }) : this.getClassification(1)
    },
    // 获取所属分类
    getClassification (detail) {
      this.$post(`${this.api.queryClassificationByType}?typeId=3`).then(({ data }) => {
        this.classifications = data
        // 如果所选分类被删除，则清空分类id
        if (detail) {
          const id = this.form.classificationId
          if (!data.find(e => e.id == id)) this.form.classificationId = ''
          this.$nextTick(() => {
            this.updateTime = 0
          })
        }
      }).catch(err => { })
    },
    // 显示所属分类弹框
    setClass () {
      this.classVisible = true
    },
    // 新增所属分类
    addClass () {
      this.classifications.find(e => e.edit) ?
        Util.errorMsg('请先保存分类！') :
        this.classifications.push({
          edit: true,
          id: '',
          classificationName: ''
        })
    },
    // 编辑所属分类
    editClass (row) {
      this.classifications.find(e => e.edit) ?
        Util.errorMsg('请先保存分类！') :
        this.$set(row, 'edit', 1)
    },
    // 删除所属分类
    delClass (row, i) {
      if (row.id) {
        this.$confirm('确定要删除吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$post(`${this.api.batchDeletionParnerClass}?ids=${row.id}`).then(res => {
            Util.successMsg('删除成功')
            this.getClassification()
          }).catch(res => { })
        }).catch(() => { })
      } else {
        this.classifications.splice(i, 1)
      }
    },
    // 提交所属分类
    submitClass (row, showMsg = 1) {
      if (!row.classificationName) return Util.errorMsg('请输入分类名称')
      this.$post(`${this.api.checkForHeavyParnerClass}?classificationName=${row.classificationName}&typeId=1&classificationId=${row.id}`).then(res => {
        this.$post(this.api[row.id ? 'updateParnerClass' : 'saveParnerClass'], {
          classificationName: row.classificationName,
          typeId: 3, // 类型(1.学习2.资讯)
          id: row.id,
        }).then(res => {
          showMsg && Util.successMsg((row.id ? '修改' : '新增') + '成功')
          this.getClassification()
        }).catch(res => { })
      }).catch(res => { })
    },
    // 关闭所属分类
    closeClass () {
      const list = this.classifications
      if (list.find(e => e.edit && e.classificationName)) {
        this.$confirm('所填写内容暂未保存，是否保存？', '提示', {
          type: 'warning',
          closeOnClickModal: false
        }).then(() => {
          list.map(e => {
            e.edit && e.classificationName && this.submitClass(e, 0)
          })
          this.classVisible = false
        }).catch(() => {
          this.classVisible = false
        })
      } else {
        this.classVisible = false
      }
      // 所选的分类被删了后，要清空所选的分类id
      if (!list.find(e => e.id == this.form.classificationId)) this.form.classificationId = ''
    },


    // 选择产品
    showProduct () {
      // this.multipleSelection = this.form.productList
      this.getCategory()
      this.checkeds = []
      // debugger
      this.productVisible = true
      this.page = 1
      this.getProduct(1)
    },
    // 获取产品分类
    async getCategory () {
      const res = await this.$get(this.api.productCategoryList)
      this.productCategories = res.classificationList
    },
    // 产品分类点击回调
    typeClick (item) {
      // this.$refs.table.clearSelection()
      this.curType = item.classificationId
      console.log("🚀 ~ file: schemeSet.vue:472 ~ typeClick ~ curType:", this.checkeds)
      this.initData()
    },
    // 产品列表
    async getProduct (set) {
      const { page } = await this.$post(this.api.listOfGoods, {
        pageNum: this.page,
        pageSize: this.pageSize,
        productClassification: this.curType,
        hotTag: 1,
        sort: 0,
        isShelves: 0,
        productName: this.keyword
      })
      this.products = page.records
      this.total = page.total

      if (set) {
        const { table } = this.$refs
        table.clearSelection()
        this.form.productList.forEach(e => {
          table.toggleRowSelection(e, true)
        })
      }
    },
    initData () {
      this.page = 1
      this.getProduct()
    },
    handleCurrentChange (val) {
      this.page = val;
      this.getProduct();
    },
    handleSelectionChange (val) {
      console.log("🚀 ~ file: schemeSet.vue:516 ~ handleSelectionChange ~ val:", val)
      this.checkeds = JSON.parse(JSON.stringify(val))
      this.multipleSelection = val
    },
    // 删除已选产品
    delProduct (i, row) {
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning"
      }).then(() => {
        this.checkeds.splice(i, 1)
      }).catch(() => { })
    },
    // 选择产品提交
    productSubmit () {
      const result = []
      this.checkeds.map(e => {
        result.push({
          mallId: e.mallId,
          productName: e.productName,
          schemeId: this.form.id
        })
      })
      this.form.productList = result
      this.productVisible = false
    },
    // 删除产品 
    delCheckedProduct (i) {
      this.form.productList.splice(i, 1)
    },

    // 附件上传之前的钩子
    fileBeforeUpload (file) {
      this.uploading++
    },
    // 文件删除
    handleRemove () {
      Oss.del(this.form.schemeFile)
      this.fileList = []
      this.form.fileName = ''
      this.form.schemeFile = ''
    },
    // 附件上传成功
    uploadSuccessFile (file) {
      this.form.fileName = file.name
      this.form.schemeFile = file.url
    },
    // 上传文件
    handleExceed (files, fileList) {
      Util.warningMsg(
        `当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！`
      )
    },
    backPage () {
      this.$router.push(this.$store.state.referrer || '/parnerOperation?type=plan')
    },
    // 返回
    back () {
      this.pass = true
      // 更改了信息才需要提示
      if (this.updateTime) {
        this.$confirm(`所填写内容暂未保存，是否保存？`, '提示', {
          type: 'warning',
          closeOnClickModal: false
        }).then(() => {
          this.submit(this.form.isRelease)
        }).catch(() => {
          this.backPage()
        })
      } else {
        this.backPage()
      }
    },
    // 更新附件的状态为发布
    updateFile (files, form, quoteId) {
      files.map(e => {
        this.$post(this.api.updateFile, {
          id: e,
          isRelease: form.isRelease,
          quote: form.title,
          quoteId
        }).then(res => { }).catch(err => { })
      })
    },
    // 提交
    submit (isRelease, next) {
      if (this.submiting) return false
      const form = JSON.parse(JSON.stringify(this.form))
      if (!form.title) return Util.errorMsg('请填写标题')
      // 如果是发布
      if (isRelease) {
        if (!form.classificationId) return Util.errorMsg('请选择所属分类')
        if (!form.applicableMajor) return Util.errorMsg('请输入适用专业')
        if (!form.schemeIntroduction) return Util.errorMsg('请输入方案简介')
        if (!form.productList.length) return Util.errorMsg('请选择产品')
        if (!form.schemeFile) return Util.errorMsg('请上传方案文件')
      }
      // if (this.uploading) return Util.errorMsg('文件正在上传，请上传完成后再发布')

      form.isRelease = isRelease
      this.submiting = true
      if (form.id) {
        this.$post(this.api.updateScheme, form).then(res => {
          Util.successMsg('修改成功')
          next ? next() : this.backPage()
        }).catch(err => {
          this.submiting = false
        })
      } else {
        this.$post(this.api.saveScheme, form).then(({ data }) => {
          Util.successMsg('创建成功')
          next ? next() : this.$router.back()
        }).catch(err => {
          this.submiting = false
        })
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.plus {
  margin-bottom: 10px;
  font-size: 18px;
  color: #062c87;
  text-align: right;
  cursor: pointer;
}

.set-btn {
  margin-left: 10px !important;
}

.manage-dia {

  .edit,
  .del {
    font-size: 14px;
    cursor: pointer;
  }

  .edit {
    margin-right: 10px;
  }
}

.input-form {
  &.model {
    height: calc(100vh - 340px);
    padding-right: 20px;
    overflow: auto;

    .el-form-item__label {
      padding-right: 20px;
    }

    .lg .el-form-item__label {
      padding-right: 43px;
    }
  }

  .item-line {
    display: flex;

    .el-form-item:not(:last-child) {
      margin-right: 200px;
    }
  }

  .line {
    margin-bottom: 24px;
    border-bottom: 1px dashed #c2c2c2;
  }

  .el-form-item--small.el-form-item {
    margin-bottom: 24px;
  }

  .el-input,
  .el-select {
    width: 300px;
  }

  .el-select .el-input {
    width: auto;
  }

  .el-textarea {
    width: 550px;
  }

  .auto,
  .auto .el-input {
    width: auto;
  }

  .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before {
    font-size: 18px;
    vertical-align: -4px;
    color: #f5222d;
  }
}

.btns {
  text-align: center;
}

.tag {
  margin: 0 5px 5px 0;
}

/deep/.product-dia {
  .product-wrap {
    display: flex;
  }

  .title-wrap {
    margin-bottom: 15px;
  }

  .item {
    width: 130px;
    max-height: 600px;
    margin-right: 20px;
    overflow: hidden;
  }

  .types {
    li {
      margin: 10px 0;
      cursor: pointer;

      &.active {
        color: #062c87;
      }
    }
  }

  .products {
    width: 400px;
  }

  .checked {
    flex: 1;

    .el-table .cell {
      font-size: 12px;
    }
  }

  .rm {
    font-size: 16px;
    cursor: pointer;
  }
}
</style>