<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"></el-cascader>

                        <el-button @click.prevent="spec_add_step(scope.row)" style="margin-left:10px">增加步骤</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,'save')"  type="text"  size="small"> 保存 </el-button> 
                    <el-button  @click.native.prevent="specal_opt(scope.$index,scope.row,'del')"  type="text"  size="small"> 删除 </el-button>                     
                    <el-button  @click.native.prevent="specal_opt(scope.$index,scope.row,'restore')"  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:[]
        }
    },
    mounted:function(){
        console.log("mounted mach_model_list");
        this.spec_mach_model_list();
    },
    methods: {
        /**提前将商品信息传入 */
        setSpecGoods(p_goods){
            this.goods = p_goods;
            console.log("pgoods ",this.goods);
        },
        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){

            console.log("111 ");
            /** 根据商品获取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];                     
                    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;
            });
            console.log("333 ");
            console.log("this.skuList  ",this.skuList );

            console.log("mach_model_list  ",this.mach_model_list );
            // 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;

                    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("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;
                        });
                    }else{

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

            this.special_tb_data = t_special_tb_data;
            console.log("this.special_tb_data ",this.special_tb_data);
            console.log("666 ");

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

            //显示窗体
            this.open = isShow
        },
        closeSpecial(tag){
            //检查有需要保存的项未提交，则提示是否确定关闭
            //TODO
            this.open = false;
        },
        openSpecial(tag){
            this.open = true;
        },
               
        /**获取商品对应的sku list  组装数据结构供页面显示，使用同步加载，避免数据回显不正常*/
        getSkuByGoodsId(goodsId){
            return new Promise((resolve,reject)=>{                
                list_sku_byGoodsId(goodsId).then((response) => {                    
                    console.log("222 ");
                   resolve(response);
                }).catch((response) => {
                    console.log("getSkuByGoodsId error",response);
                    console.log("222 e");
                    reject(response);
                });
            });
        },

        /**可选制作步骤  list  组装数据结构供页面显示，使用同步加载，避免数据回显不正常*/
        getStepListByMidAndSkuId(p_queryParams){
            return new Promise((resolve,reject)=>{        
                list_step(p_queryParams).then((response) => {        
                    console.log("getStepListByMidAndSkuId 555 ");
                    resolve(response);
                }).catch((response) => {
                    console.log("getStepListByMidAndSkuId 555 error",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];
                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 == "save"){
                console.log("special_tb_data",this.special_tb_data);
                this.spec_step_save(prow);
            }

            if(tag == "del"){
                this.spec_step_del(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){
            let step_i = prow.tb_steps.length+1
            prow.tb_steps.push({
                    "step_lab":"步骤"+step_i,
                    "step_akv":[]
                }
            );
        },
        /**获取机型列表 */
        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){
        //    {
        //     "sku_id": 1,             
        //     "risc_id": 1,            
        //     "risc_code": 1,             
        //     "risc_desc": "取杯",             
        //     "turn": 1,             
        //     "model_id": 1,            
        //     "result": 1             
        //     } 
            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);
            }
             console.log("step_ary ",step_ary);
            //提交到后台
            add_spec_step(step_ary).then((response) => {
                console.log("response ",response);
            }).catch((response) => {
                console.log("error ",response);
            });

        },
        /**删除步骤 */
        spec_step_del(prow){
            console.log("prow ",prow);
            this.queryParams={sku_id:prow.sku_id,model_id:prow.model_id};        
         
            //提交到后台
            del_spec_step(this.queryParams).then((response) => {
                console.log("response del_spec_step",response);
            }).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>