<template>
  <div>
    <xy-dialog ref="dialog" :width="70" :is-show.sync="isShow" :type="'form'" :title="$route.meta.title" :form="form"
      :rules='rules' @submit="submit">
      <template v-slot:category_ids>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>Product Phase：
          </div>
          <div class="xy-table-item-content">
            <el-select multiple collapse-tags filterable style="width:100%" v-model="form.category_ids"
              placeholder="Please Select">
              <el-option v-for="(item,index) in categoryList" :key="index" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:year>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>Year：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker style="width:100%" v-model="form.year" format="yyyy" value-format="yyyy" type="year"
              placeholder="Please Select">
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:title>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>Title：
          </div>
          <div class="xy-table-item-content">
            <el-input placeholder="Please Input" style="width:100%" v-model="form.title"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:source>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>Source：
          </div>
          <div class="xy-table-item-content">
            <el-input placeholder="Please Input" style="width:100%" v-model="form.source"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:is_top>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>Top：
          </div>
          <div class="xy-table-item-content">
            <el-select style="width:100%" v-model="form.is_top" placeholder="Please Select">
              <el-option v-for="item in [{id: 1,value: 'Yes'}, {id: 0,value: 'No'}]" :key="item.id" :label="item.value" :value="item.id"></el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:is_visible>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>Visible：
          </div>
          <div class="xy-table-item-content">
            <el-select style="width:100%" v-model="form.is_visible" placeholder="Please Select">
              <el-option v-for="item in [{id: 1,value: 'Yes'}, {id: 0,value: 'No'}]" :key="item.id" :label="item.value" :value="item.id"></el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:date>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>Sort Time：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker v-model="form.date" style="width:100%" format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="Please Select">
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:link>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>Link：
          </div>
          <div class="xy-table-item-content">
            <el-input placeholder="Please Input" style="width:100%" v-model="form.link"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:files>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>File：
          </div>
          <div class="xy-table-item-content">
            <el-upload :action="action" class='upload-demo' :limit="1" :file-list="filesList" ref="pictureUpload"
              :auto-upload="true" :data="uploadOther"  :on-progress="handleProgress" :on-success="handlesuccess" :on-remove="handleRemove">
              <el-button size="small" type="primary">upload</el-button>
            </el-upload>
            <el-progress v-if="showProgress" :percentage="uploadProgress"></el-progress>

          </div>
        </div>
      </template>

      <template v-slot:product_numbers>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>PN：
          </div>
          <div class="xy-table-item-content">
            <el-select v-loadmore="loadMore" style="width:100%" filterable v-model="form.product_numbers" multiple collapse-tags
              placeholder="Please Select">
              <el-option v-for="item in productList" :key="item.id" :label="item.number" :value="item.id">
              </el-option>
              <div v-if="productPage>lastPage" style="text-align: center;">There is no more data</div>
              <div v-else style="text-align: center;">Loading More</div>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:separation_mode>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>Separation Mode：
          </div>
          <div class="xy-table-item-content">
            <el-select style="width:100%" multiple filterable collapse-tags v-model="form.separation_mode"
              placeholder="Please Select">
              <el-option v-for="item in separationModeList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:broad_sample_type>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>Broad Sample Type：
          </div>
          <div class="xy-table-item-content">
            <el-select style="width:100%" multiple filterable collapse-tags v-model="form.broad_sample_type"
              placeholder="Please Select">
              <el-option v-for="item in applicationList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:specific_sample>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>Specific Sample：
          </div>
          <div class="xy-table-item-content">
            <el-select style="width:100%" multiple filterable collapse-tags v-model="form.specific_sample"
              placeholder="Please Select">
              <el-option v-for="item in applicationList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>

    </xy-dialog>

  </div>
</template>

<script>
  import {
    save,
    show
  } from "@/api/system/baseForm.js"
  import resource from "@/mixin/resources.js"

  import {
    index as getApplication
  } from "@/api/application/category.js"
  import {
    index as getProduct
  } from "@/api/product/index.js"
  import {
    getToken
  } from '@/utils/auth'
  export default {
    mixins: [resource],
    data() {
      return {
        table_name: 'literature_references',
        isShow: false,
        id: '',
        type: 'add',
        productPage:1,
        lastPage:0,
        productList: [],
        categoryList: [],
        applicationList: [],
        appSpecialList: [],
        uploadOther: {
          token: ""
        },
        action: `${process.env.VUE_APP_UPLOAD_API}`,
        showProgress:false,
        uploadProgress:0,
        filesList: [],
        form: {
          category_ids: [],
          application_ids: [],
          year: "",
          title: "",
          source: '',
          is_top:0,
          is_visible:1,
          date: '',
          link: '',
          files: [],
          product_numbers: [],
          separation_mode: [],
          broad_sample_type: [],
          specific_sample: [],
        },
        rules: {
          year: [{
            required: true,
            message: 'Please Input'
          }],
          title: [{
            required: true,
            message: 'Please Input'
          }],
          // link: [{
          //   required: true,
          //   message: 'Please Input'
          // }]
        }
      }
    },
    created() {
      this.uploadOther.token = getToken();
      // this.getProductList()
      this.getApplicationList()
      // this.getAppSpecial()
    },
    methods: {
      handleRemove(file, fileList) {
        this.filesList = fileList
      },
      handlesuccess(response, file, fileList) {
        if (response && response.hasOwnProperty('errcode')) {
          this.$Message.warning(response.errmsg || '')
          this.filesList = []
          return
        }
        this.filesList = fileList
      },
      handleProgress(event, file, fileList) {
        this.showProgress = true;
        this.uploadProgress = event.percent;
        console.log("uploadProgress",this.showProgress,uploadProgress,event)
      },

      async getApplicationList() {
        const res = await getApplication({
          page_size: 9999,
          page: 1,
          sort_type: 'ASC',
          sort_name: 'sort',
          // filter:[{
          //   key:'type',
          //   op:'eq',
          //   value:0
          // }]
        })
        this.applicationList = res.data
      },
      async getAppSpecial() {
        const res = await getApplication({
          page_size: 9999,
          page: 1,
          sort_type: 'ASC',
          sort_name: 'sort',
          filter: [{
            key: 'type',
            op: 'eq',
            value: 1
          }]
        })
        this.appSpecialList = res.data
      },

      async getProductList() {
        const res = await getProduct({
          page_size: 100,
          page: this.productPage
        })
        this.lastPage = res.last_page
        if(this.type==='editor'){
          const uniqueB = res.data.filter(itemB =>
              !this.form.product_numbers_details.some(itemC => itemC.id === itemB.id)
            );
            this.productList.push(...uniqueB)
        }else{
          this.productList.push(...res.data)
        }


      },
      loadMore() {
        // 这里写入要触发的方法
        this.productPage += 1;
        if(this.productPage>this.lastPage){
          return
        }
        this.getProductList();
      },

      submit() {

        if (this.id) {
          this.form.id = this.id
        } else {
          this.form.id = ''
        }
        let _files = []
        if (this.filesList.length > 0) {
          for (var h of this.filesList) {
            if (h.response) {
              _files.push(h.response.id)
            } else {
              _files.push(h.id)
            }
          }
          this.form.files = _files
        } else {
          this.form.files = []
        }
        console.log("this.form", this.form)
        // return
        save({
          table_name: this.table_name,
          ...this.form
        }).then(res => {
          this.$message({
            type: 'success',
            message: 'Success'
          })
          this.isShow = false
          this.$emit('refresh')
        })

      },

      async getDetail() {
        await show({
          table_name: this.table_name,
          id: this.id
        }).then(res => {
          this.form = this.base.requestToForm(res, this.form)
          this.form.date = res.date ? res.date : this.$moment().format('YYYY-MM-DD HH:mm:ss')

          this.form.is_visible = res.is_visible ? res.is_visible : 0
          this.form.is_top = res.is_top ? res.is_top : 0
          this.form.category_ids = res.category_ids ? res.category_ids : []
          this.form.product_numbers = res.product_numbers ? res.product_numbers : []
          this.form.separation_mode = res.separation_mode ? res.separation_mode : []
          this.form.broad_sample_type = res.broad_sample_type ? res.broad_sample_type : []
          this.form.specific_sample = res.specific_sample ? res.specific_sample : []
          if(res.product_numbers_details && res.product_numbers_details.length>0){
            this.productList.unshift(...res.product_numbers_details)
          }

          if (res.files_details && res.files_details.length > 0) {
            this.filesList = []
            res.files_details.map(item => {
              this.filesList.push({
                name: item.original_name,
                id: item.id,
                url: item.url
              })
            })
          }
        })
      }
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          if (this.type === 'editor') {
            this.getDetail()
            this.getProductList()
          } else {
            this.form.date = this.$moment().format('YYYY-MM-DD HH:mm:ss')
            this.getProductList()
          }

        } else {
          this.id = ''
          this.filesList = []
          this.showProgress = false;
          this.uploadProgress = 0;
          this.productList = []
          this.productPage = 1
          this.form = {
            category_ids: [],
            application_ids: [],
            year: "",
            title: "",
            source: '',
            is_top:0,
            is_visible:1,
            date: '',
            link: '',
            files: [],
            product_numbers: [],
            separation_mode: [],
            broad_sample_type: [],
            specific_sample: [],
          }
          this.$refs['dialog'].reset()
        }
      },
    }

  }
</script>

<style scoped lang="scss">
  ::v-deep .files{
    flex-basis: 100%;
  }
</style>
