<template>
  <div class="intelligentReplenishmentEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="intelligentReplenishmentEdit-back">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="intelligentReplenishmentEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="intelligentReplenishmentEdit-cont">
        <div class="steps-cont">
          <a-steps :current="current" size="small">
            <a-step title="产品设置" />
            <a-step title="参数设置" />
            <a-step title="系统计算" />
          </a-steps>
        </div>
        <a-form-model
          id="intelligentReplenishmentEdit-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
        >
          <!-- 产品设置 -->
          <div v-if="current==0">
            <div class="module-cont">
              <p class="title">产品范围</p>
              <a-form-model-item label=" " :colon="false" prop="stockPredictRange" class="form-item">
                <a-radio-group name="radioGroup" v-model="form.stockPredictRange" placeholder="请选择">
                  <a-radio :value="1">全部产品</a-radio>
                  <a-radio :value="0">自选产品</a-radio>
                </a-radio-group>
              </a-form-model-item>
              <productRange v-if="form.stockPredictRange==0" ref="productRange" :tableHeight="tableHeight" :itemSn="$route.params.sn" @ok="handleProductOk" />
            </div>
          </div>
          <!-- 参数设置 -->
          <div v-if="current==1">
            <div class="module-cont">
              <p class="title">销售保障法<a-button type="link" size="small" class="link-btn" @click="handleExplain('xsbz')">算法说明</a-button></p>
              <a-form-model-item label="保障倍数" prop="saleEnsureNum" class="form-item">
                <a-input-number
                  id="intelligentReplenishmentEdit-saleEnsureNum"
                  v-model="form.saleEnsureNum"
                  :precision="2"
                  :min="1"
                  :max="3"
                  placeholder="请输入1~3之间的数字，最多两位小数"
                  style="width: 100%;" />
              </a-form-model-item>
            </div>
            <div class="module-cont">
              <p class="title">趋势平均法<a-button type="link" size="small" class="link-btn" @click="handleExplain('qspj')">算法说明</a-button></p>
              <a-form-model-item label="服务水平" prop="trendSn" class="form-item">
                <div class="intelligentReplenishmentEdit-trendSn" @click="openModal=true">{{ form.serviceLevel || '--' }}%（对应的安全系数为{{ form.safetyFactor || '--' }}）</div>
              </a-form-model-item>
            </div>
          </div>
          <!-- 系统计算 -->
          <div v-if="current==2">
            <div class="item-cont">
              <img src="@/assets/explain/def_calculation.png" width="200" class="item-pic" />
              <p class="item-txt">按照上一步的参数设置，系统正在<br/>计算中...点击左上角的返回列表可查看该条预测记录</p>
            </div>
          </div>
        </a-form-model>
        <div class="btn-cont" v-if="current==0 || current==1">
          <a-button
            type="primary"
            id="intelligentReplenishmentLevel-submit"
            size="large"
            class="button-primary"
            @click="handleNext"
            style="padding: 0 60px;">下一步</a-button>
        </div>
      </a-card>
    </a-spin>
    <!-- 服务水平 -->
    <replenishment-service-level-modal :openModal="openModal" :itemSn="form.trendSn" @close="openModal=false" @ok="handleOk" />
    <!-- 算法说明 -->
    <commonModal
      :modalTit="explainType=='qspj'?'趋势平均法说明':'销售保障法说明'"
      bodyPadding="10px"
      width="1024px"
      :showFooter="false"
      :openModal="showDetailModal"
      @cancel="showDetailModal=false">
       <explainQspj v-if="explainType=='qspj'" @close="showDetailModal=false"></explainQspj>
       <explainXsbz v-if="explainType=='xsbz'" @close="showDetailModal=false"></explainXsbz>
    </commonModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import commonModal from '@/views/common/commonModal.vue'
import ReplenishmentServiceLevelModal from './serviceLevelModal.vue'
import explainQspj from './explainQspj.vue'
import explainXsbz from './explainXsbz.vue'
import productRange from './productRange.vue'
import { predictDetail, predictRangeSave, predictSave, predictTrendList, predictRun } from '@/api/predict'
export default {
  name: 'IntelligentReplenishmentEdit',
  mixins: [commonMixin],
  components: { ReplenishmentServiceLevelModal, productRange, commonModal, explainQspj, explainXsbz },
  data () {
    return {
      spinning: false,
      showDetailModal: false,
      explainType: 0,
      tableHeight: 0,
      formItemLayout: {
        labelCol: { span: 2 },
        wrapperCol: { span: 16 }
      },
      form: {
        stockPredictRange: 1,
        saleEnsureNum: '',
        trendSn: '',
        serviceLevel: '',
        safetyFactor: ''
      },
      rules: {
        saleEnsureNum: [ { required: true, message: '请输入保障倍数', trigger: 'blur' } ],
        trendSn: [ { required: true, message: '请选择服务水平', trigger: ['blur', 'change'] } ]
      },
      openModal: false,
      current: 0,
      detailData: null
    }
  },
  methods: {
    // 返回
    handleBack () {
      this.$router.push({ path: `/inventoryManagement/intelligentReplenishment/list`, query: { closeLastOldTab: true } })
    },
    // 详情
    getDetail () {
      this.spinning = true
      predictDetail({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
          this.form.stockPredictRange = res.data.stockPredictRange != undefined ? Number(res.data.stockPredictRange) : 1
          if (res.data.state == 'RUN') {
            this.current = 2
            this.spinning = false
          } else {
            this.current = 0
          }
          this.getTrendSn()
        } else {
          this.detailData = null
          this.spinning = false
        }
      })
    },
    // 产品范围 ok
    handleProductOk (params) {
      predictRangeSave(params).then(res => {
        if (res.status == 200) {
          this.$refs.productRange.refreshList()
          if (this.current == 0) { //  产品设置
            this.handleSave(true)
          }
        }
      })
    },
    // 下一步
    handleNext () {
      const _this = this
      if (this.current == 0) { //  产品设置
        this.handleSave(false)
      } else if (this.current == 1) { //  参数设置
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            const params = {
              id: this.detailData.id,
              stockPredictSn: _this.$route.params.sn,
              saleEnsureNum: _this.form.saleEnsureNum,
              trendSn: _this.form.trendSn,
              trendServiceLevel: _this.form.serviceLevel,
              trendSafetyFactor: _this.form.safetyFactor,
              stockPredictRange: this.form.stockPredictRange
            }
            _this.handleRun(params)
          } else {
            return false
          }
        })
      }
    },
    // 保存
    handleSave (noNext) {
      const params = {
        id: this.detailData.id,
        stockPredictSn: this.$route.params.sn,
        stockPredictRange: this.form.stockPredictRange
      }
      this.spinning = true
      predictSave(params).then(res => {
        if (res.status == 200) {
          if (!noNext) {
            this.current++
            this.spinning = false
          } else {
            this.getTrendSn()
          }
        } else {
          this.spinning = false
        }
      })
    },
    // 计算
    handleRun (params) {
      this.spinning = true
      predictRun(params).then(res => {
        if (res.status == 200) {
          this.current++
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 算法说明
    handleExplain (type) {
      this.explainType = type
      this.showDetailModal = true
    },
    // 服务水平选择
    handleOk (val) {
      console.log(val)
      this.form.trendSn = val.trendSn
      this.form.serviceLevel = val.serviceLevel
      this.form.safetyFactor = val.safetyFactor
      this.openModal = false
    },
    // 获取默认服务水平
    getTrendSn () {
      this.spinning = true
      predictTrendList({ defaultFlag: 1 }).then(res => {
        if (res.status == 200) {
          this.form.trendSn = (res.data && res.data[0] && res.data[0].trendSn) ? res.data[0].trendSn : undefined
          this.form.serviceLevel = (res.data && res.data[0] && res.data[0].serviceLevel) ? res.data[0].serviceLevel : undefined
          this.form.safetyFactor = (res.data && res.data[0] && res.data[0].safetyFactor) ? res.data[0].safetyFactor : undefined
        } else {
          this.form.trendSn = ''
          this.form.serviceLevel = ''
          this.form.safetyFactor = ''
        }
        this.spinning = false
      })
    },
    setTableH () {
      this.tableHeight = window.innerHeight - 550
    },
    pageInit () {
      this.form = {
        stockPredictRange: 1,
        saleEnsureNum: '',
        trendSn: '',
        serviceLevel: '',
        safetyFactor: ''
      }
      this.$refs.ruleForm.resetFields()
      this.getDetail()

      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .intelligentReplenishmentEdit-wrap{
    height: 100%;
    >.ant-spin-nested-loading{
      height: 100%;
      .ant-spin-container{
        height: 93%;
      }
    }
    .intelligentReplenishmentEdit-back{
      margin-bottom: 6px;
    }
    .intelligentReplenishmentEdit-cont{
      height: 100%;
      .steps-cont{
        width: 50%;
        margin: 30px auto 10px;
      }
      .module-cont{
        border: 1px dashed #e8e8e8;
        border-radius: 12px;
        position: relative;
        margin: 30px 0;
        padding: 20px 15px 15px;
        .title{
          position: absolute;
          left: 50px;
          top: -12px;
          padding: 0 10px;
          font-size: 15px;
          background-color: #fff;
          .link-btn{
            font-size: 12px;
          }
        }
        .form-item{
          margin-top: 25px;
        }
        .intelligentReplenishmentEdit-trendSn{
          border: 1px solid #d9d9d9;
          border-radius: 4px;
          line-height: 1.5;
          padding: 4px 11px;
          margin-top: 4px;
        }
      }
      .item-cont{
        text-align: center;
        padding: 130px 0 100px;
        .item-txt{
          margin: 20px 0 50px;
          font-size: 12px;
          line-height: 24px;
        }
      }
      .btn-cont{
        margin: 30px 0 20px;
        text-align: center;
      }
    }
  }
</style>
