<template>
  <div>
    <el-dialog title="配置制作步骤" :visible.sync="open" width="1000px" append-to-body>

        <el-table :data="special_tb_data"   style="width: 100%" ref="special_tb" @row-click="specal_tb_row_click();">
            <el-table-column label="" type="expand">
                <template slot-scope="scope">
                    <el-form label-position="left" inline>
                    <el-row  v-for="(step,step_idx) in scope.row.tb_steps" :key=step_idx  style="margin-top:5px;" >
                        <span>{{step.step_lab}}:</span>
                    
                        <el-cascader :options="scope.row.step_opts" v-model="step.step_akv"  style="margin-left:10px" :disabled="step_btn_state('diabled',scope.row,step_idx)"></el-cascader>

                        <el-button @click.prevent="spec_add_step(scope.row,step_idx)" style="margin-left:10px" :disabled="step_btn_state('disabled',scope.row,step_idx)" >增加步骤</el-button>
                        <el-button @click.prevent="spec_del_step(scope.row,step_idx)" style="margin-left:10px" :disabled="step_btn_state('diabled',scope.row,step_idx)" v-if="step_btn_show('del',scope.row,step_idx)">删除步骤</el-button>
                    </el-row>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="goods_name" >                
            </el-table-column>
            <el-table-column label="商品规格" prop="sku_spec_name">
            </el-table-column>
            <el-table-column label="机器型号" prop="model_name">
            </el-table-column>
            <el-table-column label="操作" >
                <template slot-scope="scope">
                    <el-button  @click="specal_opt(scope.$index,scope.row,'view_step')"  type="text"  size="small"> 查看步骤 </el-button> 
                    <el-button  @click.native.prevent="specal_opt(scope.$index,scope.row,'edit')"  type="text"  size="small"> {{scope.row.btnName}} </el-button> 
                    <el-button  @click.native.prevent="specal_opt(scope.$index,scope.row,'del')"  type="text"  size="small"> 删除全部步骤 </el-button>                     
                    
                </template>
            </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closeSpecial('cancel');">取 消</el-button>
            <el-button type="primary" @click="closeSpecial('confim');">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>
<script>
import { list_machine_model,list_step,add_spec_step,list_data_spec_step,del_spec_step,list_sku_byGoodsId } from "@/api/system/specification.js";
import { stringify } from "querystring";
export default {
    props: {   
    },
    data() {
        
        return{
            open:false,
            
            goods:{},
            crowext:false,
            special_tb_data:[],            
            steps:[],
            queryParams:{},
            mach_model_list:[],
            skuList:[],
            psku:null,
        }
    },
    mounted:function(){
        this.spec_mach_model_list();
    },
    methods: {
        /**提前将商品信息传入 */
        setSpecGoods(p_goods,p_sku){
            this.goods = p_goods;
            this.psku = p_sku;
            console.log("setSpecGoods",p_sku);
        },
        findSpecNameById(p_specId){
            let specList = JSON.parse(this.goods.spec);
            let specName = '';
            for(let i=0;i<specList.length;i++){
                let specId = specList[i].id;
                if(specId == p_specId){
                    specName = specList[i].name;
                    break;
                }
            }
            return specName;
        },
        buildSkuSpecName(p_sku){
            let strName = '';
            for(let i=0;i<p_sku.length;i++){
                strName +=p_sku[i].specName+":"+p_sku[i].spec_RuleName+"\n\r";
            }
            return strName;
        },
        /**打开规格详情配置，并初始化显示内容 */
        async showSpecial(isShow,p_goods){
            /** 根据商品获取sku list； 按原型组装数据*/
            await this.getSkuByGoodsId(this.goods.id).then((res)=>{
                console.log("getSkuByGoodsId response 123",res);
                let t_skuList = [];
                for(let i=0;i<res.data.length;i++){
                    let sku = res.data[i];  
                    //只显示当前sku的数据进行配置,不一致的先跳过；
                    if(this.psku.sku_id != sku.id) continue;
                    
                    let skuObj_ary = [];
                    let ruleList = JSON.parse(sku.ruleList);
                    for(let j=0;j<ruleList.length;j++){
                        let sku_spec_Obj = {};
                        let rule = ruleList[j];
                        let specName = this.findSpecNameById(rule.specId);
                        let spec_RuleName = rule.name;
                        sku_spec_Obj.specName=specName;
                        sku_spec_Obj.spec_RuleName = spec_RuleName;
                        skuObj_ary.push(sku_spec_Obj);
                    }
                    let skuObj = {};
                    skuObj.sku_id=sku.id;
                    skuObj.skuAry  = skuObj_ary;
                    t_skuList.push(skuObj);
                } 
                this.skuList = t_skuList;
            }).catch((res)=>{
                console.log("getSkuByGoodsId 123",res);
            });
            // sku，和机器型号可能的数据放到一个数组里，后续只循环一个数组即可，也为方法抽取提供条件；
            let t_special_tb_data=[]
            for(let i=0;i<this.skuList.length;i++){
                let skuObj = this.skuList[i];
                for(let j=0;j<this.mach_model_list.length;j++){
                    let mach_mode = this.mach_model_list[j];
                    let tb_data_item = {};
                    tb_data_item.mach_mode=mach_mode;
                    tb_data_item.sku = skuObj;
                    let strName = this.buildSkuSpecName(skuObj.skuAry);
                    let sku_spec_model = {
                        "goods_code":p_goods.code,
                        "goods_name":p_goods.name,
                        "sku_id":skuObj.sku_id,                         
                        "sku_spec_name":strName,
                        "model_name":mach_mode.model_name,
                        "model_id":mach_mode.id,
                        "tb_steps":[{
                            "step_lab":"步骤1",
                            "step_akv":[]
                        }],
                        "step_opts":[]
                    }
                    
                    sku_spec_model.mach_mode=mach_mode;
                    sku_spec_model.sku = skuObj;

                    sku_spec_model.btnName="编辑"
                    sku_spec_model.currOptTag='view';

                    t_special_tb_data.push(sku_spec_model);
                }
            }

           

            /** sku，和机器型号 获取可能的步骤*/
            for(let i=0;i<t_special_tb_data.length;i++){
                    let spec_sku_item = t_special_tb_data[i];
                    // sku，和机器型号可能的数据；         
                    let queryParams = {model_id:spec_sku_item.model_id,sku_id:spec_sku_item.sku_id}
                    /** 
                     * 注意！！！
                     * 可能的操作步骤是根据机器以及sku来获取的，当sku多的时候会循环多次向后台请求
                     * 当前采用同步方式，会比较慢。
                     * 先调试完成，再试试异步加载数据是否可行 /  或者如果数据都一样是不是用一份即可！！！
                     */
                    //这个判断是先用一份数据
                    // if(this.steps.length==0){
                        await this.getStepListByMidAndSkuId(queryParams).then((res)=>{
                            console.log("getStepListByMidAndSkuId res",res);
                            let step_opts = [];
                            for(let obj in  res.data){
                                //console.log(obj,spec_model.step_list[obj]);
                                let step_obj = {};
                                step_obj = res.data[obj];
                                step_obj.step_key = obj;
                                step_obj.label = step_obj.risc_desc
                                step_obj.value = step_obj.risc_id
                                let children = [];
                                let childrenObj = {};
                                let options = JSON.parse(step_obj.options);
                                for(let opt in options){
                                    childrenObj = {};
                                    childrenObj.label = opt;
                                    childrenObj.value = options[opt];
                                    children.push(childrenObj);
                                }
                                step_obj.children = children
                                step_opts.push(step_obj);
                            }
                            console.log("step_opts",step_opts);
                            //注意这里会覆盖上一个机器的步骤
                            this.steps = step_opts;
                        });


                        // list_step(queryParams).then((res) => {
                         
                        // }).catch((res) => {                    
                        
                        // });

                    // }else{

                    // }
                    //还是要每个个对象里面加上可选步骤，以后即时改动，也不用调整页面模板，只需要调整js脚本
                    spec_sku_item.step_opts = this.steps;
            }

            this.special_tb_data = t_special_tb_data;
            //回显历史数据
            this.get_step_data();

            //显示窗体
            this.open = isShow
        },
        closeSpecial(tag){
            //检查有需要保存的项未提交，则提示是否确定关闭
            if(tag == 'confim'){
                for(let i=0;i<this.special_tb_data.length;i++){
                    let item = this.special_tb_data[i];
                    if(item.currOptTag=='edit'){
                        this.$modal.msgWarning("第"+(i+1)+"行步骤编辑后未保存");
                        return ;
                    }
                }
            }
            
            this.open = false;
        },
        openSpecial(tag){
            this.open = true;
        },
               
        /**获取商品对应的sku list  组装数据结构供页面显示，使用同步加载，避免数据回显不正常*/
        getSkuByGoodsId(goodsId){
            return new Promise((resolve,reject)=>{                
                list_sku_byGoodsId(goodsId).then((response) => {                    
                 
                   resolve(response);
                }).catch((response) => {                   
                    reject(response);
                });
            });
        },

        /**可选制作步骤  list  组装数据结构供页面显示，使用同步加载，避免数据回显不正常*/
        getStepListByMidAndSkuId(p_queryParams){
            return new Promise((resolve,reject)=>{        
                list_step(p_queryParams).then((response) => {
                  resolve(response);
                }).catch((response) => {                    
                  reject(response);
                });
            });
        },


        /**获取已保存的步骤数据 */
        get_step_data(){
            this.queryParams={goods_id:this.goods.id};
            list_data_spec_step(this.queryParams).then((response) => {
                this.initStepData(response);
            }).catch((response) => {
                console.log("get_step_data error",response);
            });

           
        },
        findSkuById(p_skuid,p_modelid){
            let tb_data = null;
            for(let i=0;i<this.special_tb_data.length;i++){
                let tb_item = this.special_tb_data[i];
                if(p_skuid == tb_item.sku_id && p_modelid==tb_item.model_id ){
                    tb_data = tb_item;
                    break;
                }
            }
            return tb_data;
        },
        /**初始化已保存的步骤数据 */
        initStepData(pres){
             console.log("initStepData response",pres);
            //将后台返回的已保存的步骤数据初始化到数据结构里
            //返回的数据是商品的所有sku的配置，需要循环对应后，把数据初始化；
            for(let i=0;i<pres.data.length;i++){
                let item = pres.data[i];
                if(item.sku_id != this.psku.sku_id){
                  continue;
                }
                let tb_data = this.findSkuById(item.sku_id,item.model_id);
                console.log("initStepData tb_data",tb_data);
                let step_data = item.data;
                console.log("initStepData step_data",step_data);
                let tb_steps = tb_data.tb_steps;
                console.log("initStepData tb_steps",tb_steps);
                //如果返回的步骤有数据，将回显步骤赋值,如果没数据则初始化默认的第一个步骤，
                if(step_data && step_data.length>0){
                    tb_steps = [];
                     
                    for(let j=0;j<step_data.length;j++){
                        let step_item = step_data[j];
                        let step_num="步骤"+(j+1);
                        let step_akv=[];
                        step_akv.push(step_item.risc_code);
                        step_akv.push(step_item.result);
                        tb_steps.push({'step_lab':step_num,'step_akv':step_akv})
                    }
                    
                }else{
                    tb_steps = [{
                            "step_lab":"步骤1",
                            "step_akv":[]
                        }]
                }
                tb_data.tb_steps = tb_steps;
                console.log("initStepData tb_data.tb_steps 2",tb_data.tb_steps);
            }
 
        },
        /**列表操作 */        
        specal_opt(pindex,prow,tag){
            if(tag == "view_step"){
                this.crowext = !this.crowext;
                this.$refs.special_tb.toggleRowExpansion(prow,this.crowext)

                console.log("click view step");
            }
            if(tag == "del"){
                this.spec_step_del(prow);
            }

            if(tag == "edit"){
                console.log("prow edit ",prow);
                if(prow.currOptTag=='view'){
                    prow.btnName="保存";
                    prow.currOptTag = "edit";
                }
                else if(prow.currOptTag=='edit'){
                    this.spec_step_save(prow);
                }
                
            }
            
        },
        specal_tb_row_click(r,c,e){
            // this.testPromic(1,2823).then((response) => {
            //         console.log("xxxx",response); 
            //         console.log("spec_mach_step_list",3)
            //     });
            // console.log("spec_mach_step_list",2)
        },
        spec_add_step(prow,pidx){
            let step_i = pidx+1+1
            
            let tObj = {
                    "step_lab":"步骤"+step_i,
                    "step_akv":[]
                }
            //在当前索引下方插入一条数据
            prow.tb_steps.splice(pidx+1,0,tObj);
            this.step_sort(prow.tb_steps);
        },
        spec_del_step(prow,pidx){
            prow.tb_steps.splice(pidx,1);
            this.step_sort(prow.tb_steps);
        },
        //增加或删除后，将步骤标签重新排序
        step_sort(psteps){
            for(let i=0;i<psteps.length;i++){
                let pstep = psteps[i];
                pstep.step_lab = "步骤"+(i+1)
            }
        },
        step_btn_show(btag,prow,pidx){
            //删除按钮 如果是第一行则不可见
            if(btag == 'del'){
                if(pidx == 0){
                    return false;
                }else{
                    return true;
                }
            }
            return true;
        },
        step_btn_state(btag,prow,pidx){
           
           //按钮默认是不可用状态，根据每行是否点击了编辑按钮 ,disabled=false可编辑，=true禁用
            if(prow.currOptTag=='edit'){
                return false;
            }
            return true;
        },
        /**获取机型列表 */
        spec_mach_model_list(){
            if(this.mach_model_list.length==0){
                this.queryParams={};
                list_machine_model(this.queryParams).then((response) => {
                    this.mach_model_list = response.data;
                });
            }
        },
        /**保存步骤 */
        spec_step_save(prow){
            
            console.log("spec_step_save",prow);
            //如果步骤数据没有，提示没有编辑，最少一步。
            let t_steps = prow.tb_steps;
            if(t_steps.length==0){
                this.$modal.msgWarning("未编辑步骤信息");
                return ;
            }
            //先检查所有步骤是否有值，没有值则提示后不处理。
            for(let i=0;i<t_steps.length;i++){
                let t_step = t_steps[i];
                if(t_step.step_akv.length==0){
                    this.$modal.msgWarning(t_step.step_lab+"信息为空");
                    return;
                }
            }
           
           //如果步骤第一步不是取杯，则提示。
            if(t_steps[0].step_akv[0]!=1){
                this.$modal.msgWarning("步骤1必须是取杯");
                return ;
            }


            let step_ary = [];           
            for(let i=0;i<prow.tb_steps.length;i++){
                let step_obj =   {} 
                let t_step = prow.tb_steps[i];
                //填充对应的值
                step_obj.sku_id = prow.sku_id;
                step_obj.model_id = prow.model_id;
                step_obj = this.fillStepById(step_obj,t_step,prow);
                step_ary.push(step_obj);
            }


            this.$modal.confirm('是否确认保存当前sku操作步骤？').then(function () {
                return add_spec_step(step_ary);
            }).then((response) => {
                console.log("response ",response);
                //保存成功后将按钮还原，需要再次点击编辑才能保存
                prow.currOptTag = "view";
                prow.btnName='编辑'
                this.$modal.msgSuccess("保存成功");
            }).catch(() => { });

        },
        /**删除步骤 */
        spec_step_del(prow){
            console.log("prow ",prow);
            let t_queryParams={sku_id:prow.sku_id,model_id:prow.model_id};        
          
            this.$modal.confirm('是否确认删除当前sku操作步骤？').then(function () {
                return  del_spec_step(t_queryParams);
            }).then((response) => {
                console.log("response del_spec_step",response);
                //删除成功后将表格中对应步骤数据删除（没有从后台获取）
                prow.tb_steps=[]
                let tObj = {
                    "step_lab":"步骤"+1,
                    "step_akv":[]
                }
                prow.tb_steps.push(tObj);
                this.$modal.msgSuccess("删除成功");
            }).catch((response) => {
                console.log("error del_spec_step",response);
            });

        },
        
        fillStepById(step_obj,t_step,prow){
            //TODO
            console.log("step_obj",step_obj);
            console.log("t_step",t_step);
            console.log("prow",prow);
            let step_ak = t_step.step_akv[0];
            let step_av = t_step.step_akv[1];
            step_obj.result=step_av;
            for(let i=0;i<prow.step_opts.length;i++){
                let step_opt = prow.step_opts[i];
                if(step_opt.value == step_ak){
                    step_obj.risc_id = step_opt.risc_id
                    step_obj.risc_code =step_opt.risc_code
                    step_obj.risc_desc=step_opt.risc_desc
                    step_obj.turn=step_opt.turn
                    // for(let j=0;j<step_opt.children.length;j++){
                    //    if(step_opt.children[j].value == step_av){
                    //         step_obj.result=step_av
                    //         break;
                    //    }
                    // }

                    break;
                }
            }
            return step_obj;
        },
        /**获取可能的步骤 */
        spec_mach_step_list(model_id,sku_id){
            this.queryParams={model_id:model_id,sku_id:sku_id};
            list_step(this.queryParams).then((response) => {
                console.log("response",response);
            });
        },
        testPromic(model_id,sku_id){
            var param={model_id:model_id,sku_id:sku_id};
            return new Promise(
                function(resolve,reject){
                    list_step(param).then((response) => { 
                        resolve(response);
                    });               
            }            
            ).then(function(res){
                return res;
            }).catch(function(cat){
                return cat
            })
        }

    }
    
}
</script>