<template>
  <div ref="containerBox" class="container">
    <tabs ref="tabs" :value="menu[0]" @tab-click="toggleTab($event)">
      <tab-pane
          v-if="menu.includes('factor')"
          :disabled="disabled"
          label="因子分设置"
          name="factor"
      >
        <factor
            ref="t-factor"
            :factorList="factorList"
            @NextTab="openNextTab"
            @PreviousTab="openPreviousTab"
        />
      </tab-pane>
      <tab-pane
          v-if="menu.includes('total')"
          :disabled="disabled"
          label="总分设置"
          name="total"
      >
        <total
            ref="t-total"
            :factorList="factorList"
            :setting="setting"
            @NextTab="openNextTab"
            @PreviousTab="openPreviousTab"
        />
      </tab-pane>
      <tab-pane
          v-if="menu.includes('changmo')"
          :disabled="disabled"
          label="常模设置"
          name="changmo"
      >
        <changmo
            ref="t-changmo"
            :factorList="factorList"
            :setting="setting"
            @NextTab="openNextTab"
            @PreviousTab="openPreviousTab"
        />
      </tab-pane>
      <tab-pane
          v-if="menu.includes('warning')"
          :disabled="disabled"
          label="预警设置"
          name="warning"
      >
        <warning
            ref="t-warning"
            :factorList="factorList"
            :setting="setting"
            @NextTab="openNextTab"
            @PreviousTab="openPreviousTab"
        />
      </tab-pane>
      <tab-pane
          v-if="menu.includes('reliability')"
          :disabled="disabled"
          label="信效度设置"
          name="reliability"
      >
        <reliability
            ref="t-reliability"
            :factorList="factorList"
            :setting="setting"
            @NextTab="openNextTab"
            @PreviousTab="openPreviousTab"
        />
      </tab-pane>

      <tab-pane
          v-if="menu.includes('scoringRubric')"
          :disabled="disabled"
          label="评分规则设置"
          name="scoringRubric"
      >
        <scoring-rubric
            ref="t-scoringRubric"
            @NextTab="openNextTab"
            @PreviousTab="openPreviousTab"
        />
      </tab-pane>


      <tab-pane
          v-if="menu.includes('other')"
          :disabled="disabled"
          label="其它设置"
          name="other"
      >
        <other
            ref="t-other"
            :setting="setting"
            @NextTab="openNextTab"
            @PreviousTab="openPreviousTab"
        />
      </tab-pane>

      <tab-pane
          v-if="menu.includes('complete')"
          :disabled="disabled"
          label="设置完成"
          name="complete"
      >
        <complete
            ref="t-complete"
            :menu="menu"
            @NextTab="openNextTab"
            @PreviousTab="openPreviousTab"
            @saveAfter="saveAfter"
        />
      </tab-pane>

      <!--      <tab-pane label="测试题项" name="question">-->
      <!--        <question/>-->
      <!--      </tab-pane>-->
      <!--      <tab-pane label="条件设置" name="setting">-->
      <!--        <condition-setting/>-->
      <!--      </tab-pane>-->
    </tabs>
  </div>
</template>
<script>
import { Button, Icon, Tabs, TabPane } from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import Factor from './factor'
import Total from './total'
import Changmo from './changmo'
import Warning from './warning'
import Reliability from './reliability'
import Complete from './complete'
import Question from './question'
import ConditionSetting from './condition-setting'
import config, {
  dev,
  pre,
  prod,
  local,
  hostSuffix,
  permission,
  selectPath,
  savePath,
  upRulesTypePath,
  questionListPath,
} from './config'
import Other from './other'
import ScoringRubric from './scoring-rubric'

export default {
  name: 'y-design-form-rules',
  components: {
    ScoringRubric,
    Other,
    ConditionSetting,
    Question,
    Complete,
    Reliability,
    Warning,
    Changmo,
    Total,
    Factor,
    Button,
    Icon,
    Tabs,
    TabPane,
  },
  data () {
    return {
      menu: [],
      factorList: [],
      disabled: true,
      setting: {},
    }
  },
  props: {
    token :[Function],
    // 异常 方法
    reject: [Function],
    option: {
      type: Object,
      required: true,
    },
  },
  provide () {
    return {
      getToken: () => this.token(),
      getSetting: () =>  this.setting,
      reject: (res) => this.reject(res),
    }
  },
  watch: {
    option: {
      handler (opt) {
        this.initConfig(opt)
      },
      deep: true,
      immediate: true,
    },
  },
  created () {
    this.menu = permission()
    console.log('option:', this.option)
  },
  mounted () {
    this.$nextTick(() => {
      let width = document.getElementsByClassName('container')[0].offsetWidth
      document.getElementsByClassName('el-tabs__header')[0].style.width =
          width + 'px'
      // document.getElementsByClassName('el-tabs__header')[0].style.width = '90%'
      let list = document.getElementsByClassName('setting-top')
      for (let i = 0; i < list.length; i++) {
        list[i].style.width = width + 'px'
        // list[i].style.width = '90%'
      }
    })
  },
  destroyed () {
    console.log('组件销毁')
    // 清空缓存数据
    config.localSet('conclusion-list', {})
  },
  methods: {
    // getToken () {
    //   return this.$tool.getToken(this.setting.auth, this.setting.localAuthKey,this.setting.tokenPath ? (this.setting.host + this.setting.tokenPath) : null, this.reject)
    // },
    initConfig (opt) {
      // 初始化参数
      let { set } = new this.$tool.dataSetting.Config(this, 'setting')
      set('action', opt['action'], [
        [/dev/, 'dev'],
        [/pre/, 'pre'],
        [/prod/, 'prod'],
        [/local/, 'local'],
        [/stage/, 'stage']
      ], 'dev')

      set('host', this.setting['action'], [
        [/dev|stage/, dev()],
        [/prod/, prod()],
        [/pre/, pre()],
        [/local/, opt.host || local()]
      ])

      set('method', opt, [
        [/get/, 'get'],
        [/post/, 'post']
      ], 'get')

      set('hostSuffix', opt['action'], [
        [/prod/, '/prod-api'],
        [/stage/, '/stage-api'],
        [/dev/, '/dev-api'],
        [/pre/, '/pre-api'],
        [/local/, opt.hostSuffix || '']
      ], '/dev-api')

      set('selectPath', opt, null, selectPath())
      set('savePath', opt, null, savePath())
      set('questionListPath', opt, null, questionListPath())
      set('upRulesTypePath', opt, null, upRulesTypePath())

      set('shortId', opt)
      this.setting = Object.assign(this.option, this.setting)

      this.request()
    },
    // 初始化参数
    init (ref) {
      this.$refs[ref].loadData()
    },
    // 初始化配置
    async request () {
      // 初始化数据 获取当前量表数据库最新数据
      const { host, hostSuffix, selectPath } = this.setting
      this.$tool.request({
        url: host + hostSuffix + selectPath,
        // url: 'http://111.62.40.35:58896/stage-api' + hostSuffix + selectPath,
        method: this.setting.method,
        // method: 'GET',
        params: {
          shortId: this.setting.shortId,
        },
        headers: {
          Authorization: await this.token(),
          way: 1,
        },
      })
          .then((res) => {
            if (res.code === 200) {
              // 1. 获取到数据  判断数据是否存在
              let data = res.data || {}
              // 2.获取当前缓存数据
              let localRulesConfig = config.localGet('conclusion-list') || {}

              // 3.对比数据库和缓存shortId 是否一致
              // 4.对比数据库配置md5和缓存数据中md5 是否一致
              let result_md5 = this.$tool.crypto.md5(JSON.stringify(data))
              if (
                  localRulesConfig.shortId === this.option.shortId &&
                  ((localRulesConfig.md5 && localRulesConfig.md5 === result_md5) ||
                      result_md5 ===
                      this.$tool.crypto.md5(
                          JSON.stringify(localRulesConfig.updateData)
                      ))
              ) {
                //    继续使用update配置
                // config.localSetConclusionList('updateData', null, {})
              }
              // shortId不一致 或 shortId一致、md5不一致
              else {
                let new_config = {
                  shortId: this.option.shortId,
                  requestData: data,
                  updateData: {},
                  md5: null,
                }
                config.localSet('conclusion-list', new_config)
              }
              // 触发子组件数据加载  注意：第一位应该是 因子配置
              this.$refs['t-' + this.menu[0]].loadData()
            } else {
              this.reject(res)
            }
          })
          .catch((err) => {
            this.reject(err)
          })
    },
    // 点击tab页
    toggleTab (even) {
      // 切换tab 获取因子配置
      this.factorList = this.$refs['t-factor'].getFactor()
      this.init('t-' + even.name)
    },
    // 打开下一个tab页面
    openNextTab () {
      let tab = this.$refs['tabs']
      let nextTab =
          tab.panes[
          tab.panes.find((item) => item.name == tab.currentName)['index'] * 1 +
          1
              ]
      if (nextTab) {
        // 打开tab 页面
        tab.setCurrentName(nextTab.name)
        //  md5
        let localRulesConfig =
            config.localGet('conclusion-list', 'updateData') || {}
        config.localSetConclusionList(
            'md5',
            null,
            this.$tool.crypto.md5(JSON.stringify(localRulesConfig))
        )

        // 初始化 页面数据
        this.init('t-' + nextTab.name)
        this.factorList = this.$refs['t-factor'].getFactor()
        this.$refs.containerBox.scrollTo(0, 0)
      }
    },
    // 打开上一个tab页面
    openPreviousTab () {
      let tab = this.$refs['tabs']
      let nextTab =
          tab.panes[
          tab.panes.find((item) => item.name == tab.currentName)['index'] * 1 -
          1
              ]
      if (nextTab) {
        // 打开tab 页面
        tab.setCurrentName(nextTab.name)
        // 初始化 页面数据
        this.init('t-' + nextTab.name)
        this.factorList = this.$refs['t-factor'].getFactor()
        this.$refs.containerBox.scrollTo(0, 0)
      }
    },
    // 关闭事件
    saveAfter () {
      this.$emit('saveAfter')
    },
  },
}
</script>
<style scoped>
::v-deep .el-radio {
  width: 60px;
}

::v-deep .el-select .el-input {
  width: 130px;
}

::v-deep .el-form-item .el-radio:first-child,
.el-form-item .el-checkbox:first-child {
  margin-left: 30px;
}

::v-deep .el-tabs__item.is-top:nth-child(2) {
  padding-left: 20px;
}

::v-deep .el-tabs__header {
  position: fixed;
  /*margin: 0 0 15px;*/
  padding: 0 15px;
  background: #fff;
  z-index: 99;
  top: 40px;
  /* width: 90%; */
}

.container {
  position: absolute;
  overflow-y: auto;
  height: 90vh;
  width: 100%;
}

::v-deep .el-tabs__content {
  padding-top: 64px;
  /* min-width: 1115px; */
}

::v-deep .el-tabs__item.is-disabled {
  color: #303133 !important;
}

::v-deep .el-tabs__item.is-active {
  color: #409eff !important;
}

.changmo-setting-content {
  /* min-width: 1115px; */
}

::v-deep .setting-top {
  position: fixed;
  /* width: 90%; */
  /* min-width: 800px; */
  background: #fff;
  z-index: 98;
  top: 66px;
}

::v-deep .naxtBox {
  position: fixed !important;
  top: 94px;
}
</style>
