<template>
  <div class="saga-supplement-box">
    <div class="saga-brand-box">
      <el-tabs :tab-position="tabPosition" class="reset-steps" @tab-click="jump" v-model="stepActive">
        <el-tab-pane label="基本信息" name="0"/>
        <el-tab-pane label="技术参数" name="1"/>
        <el-tab-pane label="附件信息" name="2"/>
      </el-tabs>
      <el-form label-position="top" :model="ruleForm" :rules="rules" ref="ruleForm">
        <section class="d_jump">
          <p class="title"><i class="iconfont iconjuxing" style="color:#3A8DDE;"></i>基本信息</p>
          <el-form-item label="产品类型" prop="ProdCode">
            <el-select v-model="ruleForm.ProdCode" filterable placeholder="请选择" @change="handleChangeProduct">
              <el-option-group v-for="group in productList" :key="group.label" :label="group.text">
                <el-option v-for="item in group.options" :key="item.Code" :label="item.AliasName"
                           :value="item.Code"></el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item label="品牌" prop="BrandID">
            <el-select v-model="ruleForm.BrandID" filterable remote @change="handleChangeBrand"
                       placeholder="请选择" :remote-method="remoteMethods" :loading="loading">
              <el-option v-for="item in brandList" :key="item.BrandID"
                         :label="`${item.BrandCname}${item.BrandName?`（${item.BrandCname}）`:''}`"
                         :value="item.BrandID"/>
            </el-select>
          </el-form-item>
          <el-form-item label="型号" prop="Model">
            <el-input v-model="ruleForm.Model" />
          </el-form-item>
        </section>
        <section class="d_jump">
          <p class="title"><i class="iconfont iconjuxing" style="color:#3A8DDE;"></i>技术参数</p>
          <template v-for="item in TechnicalData">
            <el-form-item :label="item.Name" :key="item.Code">
              <el-input
                v-if="item.InputMode == 'B1' || item.InputMode == 'B2'"
                v-model="ruleForm.ProdParam[item.Code]"/>

              <el-input
                v-else-if="item.InputMode == 'A1'||item.InputMode == 'A2'"
                type="number"
                v-model="ruleForm.ProdParam[item.Code]">
                <template slot="append" v-if="item.Unit">{{item.Unit}}</template>
              </el-input>

              <el-select
                v-else-if="item.InputMode == 'D1' || item.InputMode == 'E2' || item.InputMode == 'D1L'"
                placeholder="请选择"
                v-model="ruleForm.ProdParam[item.Code]"
                clearable>
                <el-option :key="`${item.Code}-${op.code}`" :label="op.name" :value="op.code" v-for="op in item.DataSource"></el-option>
              </el-select>

              <el-select
                v-else-if="item.InputMode == 'D2'"
                placeholder="请选择"
                v-model="ruleForm.ProdParam[item.Code]"
                clearable
                multiple
                collapse-tags>
                <el-option :key="`${item.Code}-${op.code}`" :label="op.name" :value="op.code" v-for="op in item.DataSource"></el-option>
              </el-select>

              <el-select
                v-else-if="item.InputMode == 'D3'"
                placeholder="请选择"
                v-model="ruleForm.ProdParam[item.Code]"
                clearable
                multiple
                collapse-tags>
                <el-option :key="`${item.Code}-${op.code}`" :label="op.name" :value="op.code" v-for="op in item.DataSource"></el-option>
              </el-select>

              <el-date-picker
                v-else-if="item.InputMode == 'C6'"
                v-model="ruleForm.ProdParam[item.Code]"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"/>

              <!-- <el-cascader
                v-else-if="item.InputMode == 'D1L'"
                placeholder="请选择"
                :options="item.options"
                v-model="ruleForm.ProdParam[item.Code]"
                :props="item.props"
                filterable
                :show-all-levels="false"
                clearable
                style="width: 200px"/> -->

              <el-input
                v-else-if="item.InputMode == 'L'||item.InputMode == 'L1'||item.InputMode == 'L2'||item.InputMode == 'M'"
                v-model="ruleForm.ProdParam[item.Code]">
                <template slot="append" v-if="item.Unit">{{item.Unit}}</template>
              </el-input>

              <el-date-picker
                v-else-if="item.InputMode == 'C5'" v-model="ruleForm.ProdParam[item.Code]"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                type="date">
              </el-date-picker>

              <el-input v-else v-model="ruleForm.ProdParam[item.Code]"/>

            </el-form-item>
          </template>
        </section>
        <section class="d_jump">
          <p class="title"><i class="iconfont iconjuxing" style="color:#3A8DDE;"></i>附件信息</p>
          <template v-for="item in AttachmentInfo">
            <el-form-item :label="item.Name" :key="item.Code">
              <uploadFiles :readOnly="read" :defined="item.Code" :keysArr="ruleForm.ProdFile[item.Code]" @change="changeItem"/>
            </el-form-item>
          </template>
        </section>
      </el-form>
    </div>
  </div>
</template>

<script>
  import uploadFiles from "@/components/public/uploadFiles"
  import {defFuncidQuery, prodRecordQuery, prodTypeCreate, prodTypeUpdate} from "@/api/product"
  import {brandQueryByKeyword, brandRecordQuery} from "@/api/brand"
  import {mapGetters} from "vuex"

  export default {
    components: {uploadFiles},
    created() {
      this.getProdType()
      this.getBrandNum5()
    },
    mounted() {
      let listener = document.querySelector('.saga-brand-box')
      listener.addEventListener('scroll', this.onScroll)
      window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))

    },
    destroyed() {
      window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
    },
    data() {
      let checkBrand = (rule, value, callback) => {
        if (value == '') {
          return callback(new Error('请选择品牌'))
        } else {
          callback()
        }
      }
      return {
        TechnicalData: [],
        AttachmentInfo: [],
        read: false,
        loading: false,
        defaultBrandList: [],
        brandList: [],
        productList: [],
        stepActive: '0',
        tabPosition: 'left',
        ruleForm: {
          ProdCode: '',
          BrandID: '',
          Model: '',
          ProdParam: {},
          ProdFile: {},
        },
        rules: {
          ProdCode: [
            {required: true, message: '请选择产品类型', trigger: 'change'}
          ],
          BrandID: [
            {required: true, validator: checkBrand, trigger: 'blur'}
          ],
          Model: [
            {required: true, message: '请输入型号', trigger: 'blur'}
          ]
        }
      }
  },
  computed: {
    ...mapGetters('layout', ['dictionary']),
  },
  methods: {
    beforeunloadHandler(e) {
      let {BrandID, ProdCode, Model, ProdFile, ProdParam} = this.ruleForm
      // if (BrandID || ProdCode || ruleForm || Object.keys(ProdFile).length > 0 || Object.keys(ProdParam).length > 0) {
      if (BrandID || ProdCode || Model) {
        e.preventDefault();
        // 兼容IE8和Firefox之前的版本
        if (e) {
          e.returnValue = '系统可能不会保存您所做的更改'
        }
        return '系统可能不会保存您所做的更改'
      }

    },
    getProdType() {// 获取产品类型
      let params = {
        Type: this.dictionary.dictionaryType,
        GroupId: this.dictionary.groupId,
        ProjectId: this.dictionary.projectId,
      }
      prodRecordQuery(params, res => {
        res.Content.map(item => {
          if (item.label == 'record') {
            item.text = `最近使用`
          } else if (item.label == 'all') {
            item.text = ''
          }
        })
        this.productList = res.Content
        if (this.$route.params.ProdCode) {//如果是修改,加载信息点
          this.handleChangeProduct(this.$route.params.ProdCode)
        }
        if (this.$route.params.BrandID) {
          this.ruleForm.BrandID = this.$route.params.Brand.BrandID
        }
      })
    },
    getBrandNum5() {// 获取最新创建过产品型号的5个品牌(如果是修改的话只显示修改产品的品牌)
      // if (this.$route.params.Brand) {
      if (this.$route.params.Brand && Object.keys(this.$route.params.Brand).length > 0) {

        this.defaultBrandList = [this.$route.params.Brand]
        this.brandList = [this.$route.params.Brand]
      } else {
        let params = {
          Type: this.dictionary.dictionaryType,
          GroupId: this.dictionary.groupId,
          ProjectId: this.dictionary.projectId,
        }
        brandRecordQuery(params, res => {
          this.defaultBrandList = res.Content
          this.brandList = res.Content
        })
      }
    },
    handleChangeProduct(item) {// 切换产品类型
      let param = {
        Type: this.dictionary.dictionaryType,
        GroupId: this.dictionary.groupId,
        ProjectId: this.dictionary.projectId,
        ClassCode: item
      }
      defFuncidQuery(param, res => {
        this.TechnicalData = []
        this.ruleForm.ProdParam = {}
        this.ruleForm.ProdFile = {}
        res.Content.TechnicalData.forEach(group => {
          for (let key in group) {
            group[key].forEach(i => {
              if (i.DataType == 'ENUM' || i.DataType == 'MENUM') {
                i.DataSource = JSON.parse(i.DataSource)
              }
              this.TechnicalData.push(i)
            })
          }
        })
        this.AttachmentInfo = res.Content.AttachmentInfo
        if (this.$route.params.ProdCode) {//判断是否是修改,回显修改内容
          if (!this.ruleForm.ProdCode) {
            let {Brand, ProdID, prodCname, ...ruleForm} = this.$route.params
            this.ruleForm = Object.assign(this.ruleForm, ruleForm)
          }
        }
      })
    },
    handleChangeBrand(item) {// 切换品牌
      console.log(item)
    },
    jump(tab, event) {
      this.stepActive = tab.index
      let jump = document.querySelectorAll('.d_jump'),
        total = jump[this.stepActive].offsetTop,//获取需要滚动的距离
        listener = document.querySelector('.saga-brand-box'),
        distance = listener.scrollTop,
        step = total / 50;
      if (total > distance) {
        smoothDown()
      } else {
        let newTotal = distance - total + 100
        step = newTotal / 50
        smoothUp()
      }

      function smoothDown() {
        if (distance < total) {
          distance += step
          listener.scrollTop = distance
          setTimeout(smoothDown, 10)
        } else {
          listener.scrollTop = total
        }
      }

      function smoothUp() {
        if (distance > total) {
          distance -= step
          listener.scrollTop = distance
          setTimeout(smoothUp, 10)
        } else {
          listener.scrollTop = total
        }
      }
    },
    onScroll() {
      let scrolled = document.querySelector('.saga-brand-box').scrollTop
      let jump = document.querySelectorAll('.d_jump')
      for (let i = 0; i < jump.length; i++) {
        if (jump[i].offsetTop >= scrolled) {
          this.stepActive = i.toString()
          break
        }
      }
    },
    remoteMethods(query) {// 品牌搜索(显示50条)
      if (query !== '') {
        this.loading = true
        brandQueryByKeyword({keyword: query, PageSize: 50,}, res => {
          this.loading = false
          this.brandList = res.Content
        })
      } else {
        this.brandList = this.defaultBrandList
      }
    },
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        let type = {
          Type: this.dictionary.dictionaryType,
          GroupId: this.dictionary.groupId,
          ProjectId: this.dictionary.projectId,
        }
        if (valid) {
          if (this.$route.params.ProdID) {//修改
            let params = {
              Content: [{ProdID: this.$route.params.ProdID, ...this.ruleForm}]
            }
            prodTypeUpdate(params, res => {
              this.$message.success('修改成功！')
              this.$router.go(-1)
            })
          } else {//添加
            let param = Object.assign(this.ruleForm, {
              Type: this.dictionary.dictionaryType,
              GroupId: this.dictionary.groupId,
              ProjectId: this.dictionary.projectId,
            })
            let params = {
              Content: [param]
            }
            prodTypeCreate(params, res => {
              this.$message.success('创建成功！')
              this.$router.push('/product')
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let param = Object.assign(this.ruleForm, {
            Type: this.dictionary.dictionaryType,
            GroupId: this.dictionary.groupId,
            ProjectId: this.dictionary.projectId,
          })
          let params = {
            Content: [param]
          }
          prodTypeCreate(params, res => {
            this.$message.success('创建成功！')
            this.ruleForm.ProdParam = {}
            this.ruleForm.ProdFile = {}
            this.ruleForm.Model = ''
          })
        } else {
          return false;
        }
      });
    },

    changeItem(files, code) {
      this.ruleForm.ProdFile[code] = files
    }
  },
  watch: {}
}
</script>
<style lang="scss" scoped>
.saga-supplement-box {
  position: relative;
  height: 100%;
  margin-top: 90px;
  background: #fff;

  .saga-brand-box {
    width: 100%;
    height: 100%;
    padding: 16px;
    box-sizing: border-box;
    background: rgba(255, 255, 255, 1);
    overflow-y: auto;

    .reset-steps {
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
    }

    .d_jump {
      display: inline-block;
      width: calc(100% - 108px);
      position: relative;
      left: 100px;

      .title {
        margin: 25px 70px;
        padding-bottom: 10px;
        font-size: 16px;
        color: #1f2429;
        border-bottom: 1px solid #eff0f1;
      }

      .el-select,/deep/ .el-form-item__content, .el-cascader {
        width: 320px;
      }
    }

    .el-form-item--mini.el-form-item,
    .el-form-item--small.el-form-item {
      padding: 0 340px;
    }
  }

  /deep/ .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

::-webkit-scrollbar-thumb {
  height: 50px;
  outline-offset: -2px;
  outline: 2px solid #dddee0;
  border: 2px solid #dddee0;
  background-color: #dddee0;
  border-radius: 4px;
}

::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}
</style>
