<template>
  <div class="manage-root cdkey-create">
    <Header />
    <div class="manage-root-contain">
        <nav-menu class="manage-root-contain-left" :activeMenuIndex="activeMenuIndex"></nav-menu>
        <div class="manage-root-contain-right">
            <breadcrumb :breadcrumbList="breadcrumbList" class="breadcrumb-box"></breadcrumb>
            <div class="create-top">
                <div class="common-title-box">
                    <h3>{{id?'编辑兑换码':'创建兑换码'}}</h3>
                    <div class="btn-box" v-if="id||!id&&stepIndex!==2">
                        <el-button size="small" :disabled="true">上一步</el-button>
                        <el-button type="primary" size="small" @click="handleStep('+')" :disabled="stepIndex===2" :loading="loading">下一步</el-button>
                    </div>
                </div>
                <el-steps :active="stepIndex" align-center>
                    <el-step title="基本信息" description="填写兑换码基本信息">
                        <svg-icon icon-class="dot" slot="icon" class="svg-dot"></svg-icon>
                    </el-step>
                    <el-step :title="id?'编辑兑换内容':'添加兑换内容'" description="为兑换码添加内容">
                        <svg-icon icon-class="dot" slot="icon" class="svg-dot"></svg-icon>
                    </el-step>
                    <el-step :title="id?'完成编辑':'完成创建'" :description="id?'兑换码编辑完成':'兑换码创建完成'">
                        <svg-icon icon-class="dot" slot="icon" class="svg-dot"></svg-icon>
                    </el-step>
                </el-steps>
            </div>
            <div class="create-bottom">
                <el-form :model="organizeForm" :rules="rulesOrganize" ref="organizeForm" label-width="100px" class="registerForm" v-if="stepIndex===0">
                    <el-form-item label="兑换码名称" prop="name">
                        <el-input v-model="organizeForm.name" placeholder="请输入兑换码名称" @blur="handleTrim('organizeForm','name')" maxlength="20"></el-input>
                        <p class="tips">不超过20个字</p>
                    </el-form-item>
                    <el-form-item label="可使用人数" prop="person_count_max" class="price-box" v-if="type===0">
                        <el-input-number v-model="organizeForm.person_count_max" @change="handleChange" :min="0" :max="500" size="small" class="personal-ceil"></el-input-number>
                        <span class="append">人</span>
                        <p class="tips">最多不超过 500 次</p>
                    </el-form-item>
                    <el-form-item label="有效期" prop="valid_day_count" class="validity-box">
                        <el-input placeholder="请输入内容" v-model="organizeForm.valid_day_count" type="number" :min="1" maxlength="20">
                            <template slot="append">天</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="兑换码" prop="subcode_import_file_id" v-if="type===1">
                        <div class="article-mp3-box">
                            <ul v-if="organizeForm.subcode_import_file_list&&organizeForm.subcode_import_file_list.length>0" class="article-mp3-list">
                                <li v-for="(item,index) in organizeForm.subcode_import_file_list" :key="index">
                                    <a><svg-icon :icon-class="'txt'" class="icon-logo"></svg-icon><span>{{item.name}}</span></a>
                                    <i class="el-icon-error" @click="handleDelResource(index)"></i>
                                </li>
                            </ul>
                            <upload :class="['article-mp3']" :datafileList="organizeForm.subcode_import_file_list" :changeFillId="handleAvatarSuccess" :fileName="'articleMp3'" uploadType="txt" tips=' ' :filleNumber="1" :showList="true" />
                        </div>
                    </el-form-item>
                    <el-form-item label="备注" prop="memo">
                        <el-input
                            type="textarea"
                            :rows="4"
                            placeholder="请输入"
                            v-model="organizeForm.memo"
                            maxlength="200"
                            show-word-limit>
                        </el-input>
                    </el-form-item>
                </el-form>
                <div v-if="stepIndex===1">
                    <div class="issue-top">
                        <h4 class="issue-top-left">
                            内容列表
                        </h4>
                        <el-button type="primary" size="small" @click="addGoods">添加内容</el-button>
                    </div>
                    <el-table
                        class="search-table"
                        :data="tableData"
                        style="width: 100%"
                        @sort-change="handleSort"
                        :default-sort = dataSort
                        :max-height="tableHeight"
                        v-loading="tableLoading">
                        <el-table-column
                            type="index"
                            label="#"
                            sortable
                            width="54"
                            :index="(pageNumber-1)*pageSize+1">
                        </el-table-column>
                        <el-table-column
                            prop="goods_name"
                            label="名称"
                            sortable="custom">
                        </el-table-column>
                        <el-table-column
                            prop="goods_type"
                            label="类型"
                            sortable="custom"
                            width="150" >
                            <template slot-scope="scope">
                                <span class="items-type" :style="{background:goodsTypeListCss[scope.row.goods_type]?goodsTypeListCss[scope.row.goods_type].bg:'', color:goodsTypeListCss[scope.row.goods_type]?goodsTypeListCss[scope.row.goods_type].color:''}">{{scope.row.goods_type_name}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="goods_study_phase"
                            label="学段"
                            sortable="custom"
                            width="120">
                            <template slot-scope="scope">
                                {{scope.row.goods_study_phase_name}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            fixed="right"
                            label="操作"
                            width="180">
                            <template slot-scope="scope">
                                <el-button
                                    @click.native.prevent="handleDelete(scope.row, scope.$index)"
                                    type="text"
                                    size="small"
                                    class="red-btn">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageNumber"
                        :page-sizes="[10, 20, 30, 40]"
                        :page-size="pageSize"
                        layout="total, prev, pager, next, sizes, jumper"
                        :total="total_count">
                    </el-pagination>
                </div>
                <div v-if="stepIndex===2">
                    <el-result icon="success" :subTitle="id?'兑换码编辑成功':'兑换码创建成功'">
                        <template slot="extra">
                            <el-button size="small" @click="handleback">返回列表</el-button>
                            <el-button type="primary" size="small" @click="handleCreate">继续创建</el-button>
                        </template>
                    </el-result>
                </div>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
import Header from "../../components/Header.vue";
import NavMenu from "../../components/NavMenu.vue"
import Breadcrumb from '../../components/Breadcrumb.vue';
import { getLogin } from "@/api/ajax";
import Upload from "../../components/Upload.vue"

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Header, NavMenu, Breadcrumb, Upload },
  props: {},
  data() {
    //这里存放数据
    const validateValidity = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入有效期'));
        } else {
            if (value<1) {
                callback(new Error('请输入有效期'));
            } else {
                callback();
            }
        }
    };
    return {
        goodsTypeListCss:{
            2:{
                text:'报纸',
                color:'#165DFF',
                bg:'#E8F7FF'
            },
            // '2':{
            //     text:'画刊',
            //     color:'#F53F3F',
            //     bg:'#FFECE8'
            // },
            '3':{
                text:'精读',
                color:'#0FC6C2',
                bg:'#E8FFFB'
            },
            0:{
                text:'课程',
                color:'#722ED1',
                bg:'#F5E8FF'
            },
            1:{
                text:'课程',
                color:'#722ED1',
                bg:'#F5E8FF'
            },
            10:{
                text:'课程',
                color:'#722ED1',
                bg:'#F5E8FF'
            },
            // '5':{
            //     text:'报纸专辑',
            //     color:'#165DFF',
            //     bg:'#E8F7FF'
            // },
            // '6':{
            //     text:'画刊专辑',
            //     color:'#F53F3F',
            //     bg:'#FFECE8'
            // }
        },
        activeMenuIndex: "cdkey_manage",
        breadcrumbList:[
            {
                icon:'barcode-line',
                url:'',
                text:''
            },
            {
                icon:'',
                url:'',
                text:'兑换码管理'
            }
        ],
        id:this.$route.query.id?this.$route.query.id:'',
        organizeForm:{
            name: '',
            person_count_max: 50,
            valid_day_count: 30,
            memo: '',
            subcode_import_file_list: [], 
            subcode_import_file_id: '', 
            type: this.$route.query.type?this.$route.query.type*1:0
        },
        rulesOrganize:{
            name:[
                { required: true, message: '请输入兑换码名称', trigger: 'blur' },
                { max: 20, message: '兑换码名称最多20位', trigger:'change' },
            ],
            person_count_max:[
                { required: true, message: '请输入可使用人数', trigger: 'blur' }
            ],
            valid_day_count:[
                { required: true, validator: validateValidity, trigger: 'blur' }
            ],
            subcode_import_file_id:[
                { required: true, message: '请上传兑换码文件', trigger: 'blur' }
            ],
        },
        stepIndex:window.localStorage.getItem('cdKeyId')?1:0, // 步骤索引
        loading: false,
        cdKeyId: window.localStorage.getItem('cdKeyId')?window.localStorage.getItem('cdKeyId'):'',
        tableLoading: false,
        pageSize: 10, 
        pageNumber: 1,
        tableHeight: "", // 表格高度
        total_count: 0,
        dataSort: {},
        tableData: [],
        type: this.$route.query.type?this.$route.query.type*1:0,
    }
  },
  //计算属性 类似于data概念
  computed: {
    
  },
  //监控data中数据变化
  watch: {
    
  },
  //方法集合
  methods: {
    // 删除
    handleDelete(row){
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            let Mname = "/ShopServer/Manager/DiscountCodeManager/DeleteGoodsFromDiscountCode";
            let data = {
                discount_code_id: this.cdKeyId,
                goods_type: row.goods_type,
                goods_id: row.goods_id
            };
            getLogin(Mname, data).then(res => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.getGoodsList()
            });
        }).catch(() => {
               
        });
    },
    // 删除资源文件
    handleDelResource(i){
        this.$confirm("确定删除吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            this.organizeForm.subcode_import_file_list.splice(i, 1);
            this.organizeForm.subcode_import_file_id = ''
            this.$forceUpdate()
        });
    },
    handleAvatarSuccess(fileList,name) {
        this.organizeForm.subcode_import_file_list = fileList
        this.organizeForm.subcode_import_file_id = fileList[0]&&fileList[0].response&&fileList[0].response.file_info_list&&fileList[0].response.file_info_list[0]?fileList[0].response.file_info_list[0].file_id:''
        this.$forceUpdate()
    },
    handleSizeChange(val) {
        this.pageSize = val
        this.pageNumber = 1
        this.getGoodsList()
    },
    handleCurrentChange(val) {
        this.pageNumber = val
        this.getGoodsList()
    },
    handleSort(value){
        let dataSort = {
            prop: value.prop,
            order: value.order
        }
        this.dataSort = dataSort
        this.getGoodsList()
    },
    // 上一步下一步
    handleStep(type){
        if(type=='-'){
            // if(this.stepIndex>0) this.stepIndex--
        }else{
            if(this.stepIndex===0) {
                this.$refs['organizeForm'].validate((valid) => {
                    if (valid) {
                        this.handleCreateCdkey()
                    } else {
                        return false;
                    }
                });
            }else if(this.stepIndex===1){
                this.stepIndex++
            }
        }
    },
    changeIcon(flag){
        this[flag] = !this[flag]
    },
    // 返回列表
    handleback(){
        localStorage.setItem("pageNumber",1)
        this.$router.push({
            path: "/cdkey_manage",
            query: {
                
            },
        });
    },
    //继续创建
    handleCreate(){
        window.localStorage.removeItem('cdKeyId')
        this.$router.replace('/createCdkey')
        location.reload()
    },
    handleChange(value) {
        // console.log(value)
    },
    handleCreateCdkey(){
        this.loading = true
        let MethodName = "/ShopServer/Manager/DiscountCodeManager/CreateDiscountCode";
        let form = this.organizeForm
        let data = form
        getLogin(MethodName, data)
        .then((res) => {
            this.loading = false
            if(res.status===1){
               this.cdKeyId = res.id
               this.stepIndex++
               window.localStorage.removeItem('cdKeyId')
               this.getGoodsList()
            }
        })
        .catch(() => {
            this.loading = false
        });
    },
    // 去掉前后空格
    handleTrim(form,fild){
        this[form][fild] = this[form][fild].trim()
    },
    getGoodsList(){
        this.tableLoading = true
        let MethodName = "/ShopServer/Manager/DiscountCodeManager/PageQueryDiscountCodeGoodsList";
        let order_column_list = []
        if(this.dataSort != {}){
            if(this.dataSort.order=='descending'){
                order_column_list = [this.dataSort.prop + ':desc']
            }else if(this.dataSort.order=='ascending'){
                // 升序不传值
                order_column_list = [this.dataSort.prop]
            }else{
                order_column_list = ['create_time:desc']
            }
        }else{
            order_column_list = ['create_time:desc']
        }
        let data = {
            discount_code_id: this.cdKeyId,
            page_capacity:this.pageSize,
            cur_page:this.pageNumber,
            order_column_list: order_column_list
        }
        getLogin(MethodName, data)
        .then((res) => {
            this.tableLoading = false
            if(res.status===1){
               this.tableData = res.goods_list
               this.total_count = res.total_count
            }
        })
        .catch(() => {
            this.tableLoading = false
        });
    },
    // 添加商品
    addGoods(){
        window.localStorage.setItem('cdKeyId',this.cdKeyId)
        this.$router.push({
            path:'/addGoods'
        })
    },
    //计算table高度(动态设置table高度)
    getTableHeight() {
      let tableH = 460; //距离页面下方的高度
      let tableHeightDetil = window.innerHeight - tableH;
      if (tableHeightDetil <= 300) {
        this.tableHeight = 300;
      } else {
        this.tableHeight = window.innerHeight - tableH;
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    let obj = {
        icon:'',
        url:'',
        text:'创建兑换码'
    }
    if(this.id){
        obj.text = '编辑兑换码'
        // this.getCourseInfo()
    }
    this.breadcrumbList.push(obj)
    this.getTableHeight()
    if(this.stepIndex===1){
        this.getGoodsList()
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  //生命周期-创建之前
  beforeCreated() { },
  //生命周期-挂载之前
  beforeMount() { },
  //生命周期-更新之前
  beforUpdate() { },
  //生命周期-更新之后
  updated() { },
  //生命周期-销毁之前
  beforeDestory() { },
  //生命周期-销毁完成
  destoryed() { },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() { }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.create-top{
    background: #FFFFFF;
    border-radius: 4px;
    padding: 24px;
    .common-title-box{
        margin-bottom: 4px;
    }
}
.create-bottom{
    padding: 40px 40px;
    margin-top: 16px;
    background: #FFFFFF;
    border-radius: 4px;
    height: calc(100vh - 292px);
    overflow: auto;
    .tips{
        margin: 0;
        color: #86909C;
        font-size: 12px;
        line-height: 20px;
    }
    .issue-top{
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        &-left{
            margin: 0;
            color: #1D2129;
            font-size: 20px;
            font-weight: 500;
            line-height: 28px;
            span{
                margin-left: 4px;
                color: #86909C;
                font-size: 14px;
                font-weight: 400;
                line-height: 22px;
            }
        }
    }
}
.items-type{
    padding: 1px 8px;
    font-weight: 500;
    font-size: 14px;
    line-height: 22px;
    border-radius: 2px;
}
.article-mp3-box{
    display: flex;
    height: 32px;
    align-items: center;
}
.article-mp3{
    width: 82px;
    height: 32px;
    font-size: 0;
    &-has{
        width: 320px;
    }
}
.article-mp3-list{
    list-style: none;
    margin: 0;
    padding: 0;
    display: inline-block;
    width: 226px;
    li{
        padding: 5px 12px;
        height: 32px;
        border-radius: 2px 0px 0px 2px;
        background: #F2F3F5;
        display: flex;
        align-items: center;
        a{
            color: #1D2129;
            display: flex;
            align-items: center;
            flex: 1;
            span{
                overflow:hidden;
                text-overflow:ellipsis;
                white-space: nowrap;
                flex: 1;
                display: block;
                font-size: 14px;
                line-height: 22px;
                width: 163px;
            }
            .svg-icon{
                width: 16px;
                height: 16px;
                margin-right: 4px;
                color: #1D2129;
            }
        }
        .el-icon-error{
            color: #4E5969;
            cursor: pointer;
            margin-left: 4px;
        }
    }
}
</style>

<style lang="scss">
.cdkey-create{
    .personal-ceil{
        width: 200px;
        .el-input__inner{
            width: 200px;
            padding: 0 60px;
        }
    }
    .el-range-input{
        background: #F2F3F5;
    }
    .el-tag{
        background: #fff;
    }
    .validity-box{
        width: 350px;
        .el-input-group{
            width: 250px;
        }
        .el-input-group__append{
            border: none;
            border-left: 1px solid #E5E6EB;
            background: #F2F3F5;
        }
    }   
    .price-box{
        width: 300px;
        display: inline-block;
        .el-form-item__content{
            position: relative;
            .prepend,.append{
                position: absolute;
                left: 44px;
                font-size: 14px;
                line-height: 22px;
                color: #1D2129;
                line-height: 34px;
            }
            .append{
                left: 142px;
            }
        }
    }
}
.el-date-picker__editor-wrap{
    .el-input, .el-textarea{
        width: auto;
    }
}
</style>