<template>
    <lj-win-common :title="title" :show-back="true" ref="baseWin">

        <mu-button flat slot="header_right" @click="handleSubmit" style="margin-top: 8px; height: 32px" color="#2196f3">
            保存
        </mu-button>

        <template slot="body">
            <template>
                <lj-dictionary :data="ware" :columns="dictColumns" :editing="ifedit"
                    @row-icon-click="handleIconClick"></lj-dictionary>
            </template>

            <van-cell-group>
                <template slot="title">
                    <div class="flex" style="position: relative;">
                        <div class="title flex-1">
                            工艺步骤
                        </div>
                        <div class="cell-group-filter" v-if="ifSortMx">
                            <van-button round type="default" size="small" @click="handleSortMx">
                                <i class="iconfont icon-descending"></i>
                                编号排序
                            </van-button>
                        </div>
                    </div>
                </template>
            </van-cell-group>
            <van-form ref="routeForm">
                <van-cell-group van-cell-group class="lj-van-cell-group" inset v-for="(item,index) in ware.routemxList" :clickable="true">
                    <div class="save-tag" v-if="item.rowNum == 0">
                        待保存
                    </div>
                    <route-form-item
                        :key="'routeItem' + index"
                        :data="item"
                        :columns="formColumns"
                        :editing="ifedit"
                        @fileBottomNav="handleDelImg(arguments, index)"
                        @fileAdd="handleAddImg(index)"
                        @cellRightIcon="handleCellRightIcon(arguments, index)"
                        @cellInput="handleCellInput(arguments, index)"
                    />
                </van-cell-group>
            </van-form>

            <van-row type="flex" justify="center" style="margin-top:24px">
                <van-col span="16">
                    <van-button color="#2196f3" icon="plus" plain block round @click="handleAddRoutemx">新增步骤</van-button>
                </van-col>
            </van-row>

            <van-action-sheet
                v-model="fjmxState"
                :actions="fjActions"
                :description="fjDescription"
                cancel-text="取消"
                close-on-click-action
                get-container="body"
                @select="handleSelFjAction"
            >
                <template slot="description" v-if="fjActions.length == 1">
                    {{ fjDescription }}
                    <div v-if="ware.routemxList[fjmxIndex].modemp" style="position: absolute; bottom: 0; width: 100%; text-align: center; font-size: 12px; color: rgba(60, 60, 67, 0.3)">
                        上次修改：{{ `${ware.routemxList[fjmxIndex].modemp} ${ware.routemxList[fjmxIndex].moddate}` }}
                    </div>
                </template>
            </van-action-sheet>
        </template>
        <!-- <template slot="footer">
            <mu-col tag="mu-button" color="blue" @click="handleSubmit">保存</mu-col>
        </template> -->
    </lj-win-common>
</template>

<script>
    import ljWinCommon from "components/lj-win-common";
    import LjDictionary from "components/lj-dictionary";
    import RouteFormItem from "./route-form-item.vue"

    export default {
        components: {
            ljWinCommon,
            LjDictionary,
            RouteFormItem
        },
        data() {
            return {
                ifedit: true,
                // dialogFiles: [],
                mtrlMsg:{},
                ware: {},
                // hiscus:[],
                empid: 0,
                title: "工序工艺路线-新建",
                winType: 0,
                // base64Temp: "",
                // hasWrkgrp: true,
                inwareid: 0,
                // uselocationState: false, // 使用新仓位模式
                editRowIndex: 0, // 记录仓位的明细行数
                iforder: false,
                configState: false,
                editProperty: '',
                locaBasicMsg: {
                    storageid: 0,
                    mtrlcode: "",
                    mtrlname: "",
                    location_str: "",
                    pz: "",
                    planqty: 0,
                },
                apiName: "inware-cp-edit",
                dwname: "L1APP",
                gridColumns: [],
                selectedItems: [],
                batchEditing: false,
                formColumns: [
                    {label: "步骤编号", property: "code", placeholder: "填写工艺步骤编号", rules: [{ required: true, message: '必填' }], rightIcon: "ellipsis" },
                    {label: "步骤名称", property: "routestr", placeholder: "填写工艺步骤名称", rules: [{ required: true, message: '必填' }]},
                    {label: "步骤说明", property: "context", placeholder: "填写工艺步骤说明", inputLine: 2, maxlength: 120, autosize: {maxHeight: 160}},
                    {type: "file", property: "filedatas"},
                ],
                fjDescription: "",
                fjmxState: false,
                fjmxIndex: 0,
                fjActions: [],
                ifSortMx: false, // 是否排序明细
            }
        },
        created() {
            let self = this;
            this.empid = $lj.getStorage("userInfo").empid;
            var pageParm = $lj.getPageParam();
            this.title = pageParm.winType == 1 ? '工序工艺路线-修改' : '工序工艺路线-新建'
            this.winType = pageParm.winType ? pageParm.winType : 0;
            this.inwareid = pageParm.ware.inwareid;

            this.setGridColumns();

            this.ware = pageParm.ware;
            //新建
            if (this.winType == 0) {
            //     this.ware = pageParm.ware;
                this.$set(this.ware, 'routemxList', []);
            }
            // else {
            //修改
                
            //     // this.ware.Listmx.forEach(element => {
            //     //     element.status = element.status == '' ? '请选择' : element.status;
            //     //     element.woodcode = element.woodcode == '' ? '请选择' : element.woodcode;
            //     //     element.pcode = element.pcode == '' ? '请选择' : element.pcode;
            //     //     element.location = element.location == '' ? '请选择仓位' : element.location;
            //     // });
            // }

        },
        mounted(){
        },
        methods: {
            handleSortMx() {
                this.ware.routemxList.sort((a, b) => {
                    return a.code - b.code
                });
                this.ifSortMx = false;
            },
            handleCellInput(arg, idx) {
                let {row, column, rowIndex} = arg[0];
                this.ware.routemxList[idx].rowNum = 0;

                if (column.property == 'code') {
                    this.ifSortMx = true;
                }
            },
            /**右侧图标点击事件 */
            handleCellRightIcon(arg, idx) {
                let {row, column} = arg[0];

                console.log(' handleCellRightIcon :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(column));
                if (column.property == 'code') {
                    let _title = "操作";
                    if (row.code || row.routestr) {
                        _title = "工艺步骤" + row.code + " " + row.routestr;
                    }
                    this.fjDescription = _title;
                    this.fjActions = [
                        {id: 0, name: '删除步骤'},
                    ],
                    this.fjmxState = true;
                    this.fjmxIndex = idx;
                }
            },
            /**新增步骤 */
            handleAddRoutemx() {
                this.ware.routemxList.push({
                    code: "",
                    routestr: "",
                    context: "",
                    filedatas: [],
                    rowNum: 0,
                    printid: 0,
                })
            },
            /**弹出图片选项 */
            handleAddImg(idx) {
                this.fjDescription = "选择文件类型";
                this.fjActions = [
                    {id: 0, name: '图片'},
                    {id: 1, name: '视频'}
                ],
                this.fjmxState = true;
                this.fjmxIndex = idx;
            },
            handleSelFjAction(item) {
                if (item.name == "删除步骤") {
                    // $lj.selectDialog("提示", "确认删除此工艺步骤", ['删除', '取消'], (ret) => {
                    //     if (ret == 1) {
                            this.ware.routemxList.splice(this.fjmxIndex, 1);
                        // }
                        this.fjmxState = false;
                    // })
                } else {
                    switch (item.id) {
                        case 0: // 图片
                            $lj.getPictureArr((thumbPath, ret, fileType, fileName) => {
                                this.ware.routemxList[this.fjmxIndex].filedatas.push({
                                    thumbPath: thumbPath,
                                    base64: ret,
                                    fileType: fileType,
                                    fileName: fileName,
                                    ClassID: 0,
                                    relid: this.ware.routeid,
                                    relidmx: this.fjmxIndex,
                                })
                                this.ware.routemxList[this.fjmxIndex].rowNum = 0;
                            })
                            break;
                        case 1: // 视频
                            $lj.getVideoFileArr((thumbPath, base64, fileType, fileName, path) => {
                                this.ware.routemxList[this.fjmxIndex].filedatas.push({
                                    thumbPath: thumbPath,
                                    base64: base64,
                                    fileType: fileType,
                                    fileName: fileName,
                                    ClassID: 0,
                                    relid: this.ware.routeid,
                                    relidmx: this.fjmxIndex,
                                    url: path
                                })
                                this.ware.routemxList[this.fjmxIndex].rowNum = 0;
                            });
                            break;
                    }
                }
            },
            /**删除图片 */
            handleDelImg(arg, idx) {
                let {row, column, rowIndex} = arg[0];
                console.log('handleDelImg idx :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(idx));
                console.log('handleDelImg i :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(rowIndex));
                this.ware.routemxList[idx].filedatas.splice(rowIndex,1);
                this.ware.routemxList[idx].rowNum = 0;
            },
            handleButtonMenuToolsEvents(methodName){
                switch(methodName){
                    case "allcheck":
                        this.ware.Listmx.forEach((element) => {
                            this.$set(element,'checked',!element.checked);
                            if (element.checked) {
                                this.selectedItems.push(element);
                            } else {
                                let itemsTemp = [];
                                for (let item of this.selectedItems) {
                                    if (item !== element) {
                                        itemsTemp.push(item);
                                    }
                                }
                                this.selectedItems = itemsTemp;
                            }
                        })
                        break;
                    case "delete":
                        for(let i = this.ware.Listmx.length - 1;i >= 0;i--){
                            if(this.ware.Listmx[i].checked){
                                this.ware.Listmx.splice(i,1);
                            }
                        };
                        break;
                    case "add":
                        // 添加明细
                        this.handleAddMx('');
                        break;
                    case "clean":
                        // 清空明细
                        this.cleanMx();
                        break;
                    case "setting":
                        this.$refs.buttonMenu.handleLayoutSetting({dwname:this.dwname,apiName:this.apiName,gridColumns:this.gridColumns});
                        // 布局设置
                        break;
                    case "batchSetting":
                        this.batchEditing = true;
                        this.setGridColumns();
                        break;
                    case "finish":
                        if(this.selectedItems.length > 0){
                            // 完成
                            for (let item of this.selectedItems) {
                                item.checked = false;
                            }
                            let i = 0;
                            for(let mx of this.ware.Listmx) {
                                mx.printid = ++i;
                            }
                            this.selectedItems = [];
                        }
                        this.batchEditing = false;
                        this.setGridColumns();
                        break;
                    case "plan":
                        this.iforder = !this.iforder;
                        break;
                    default:
                        break;
                }
            },
            setGridColumns(data) {
                var result = [
                    {label: "行", property: "printid", width: screen.width * 0.1},
                    {label: "指令单号", property: "pordercode"},
                    {label: "物料编码", property: "mtrlcode"},
                    {label: "物料名称", property: "mtrlname"},
                    {label: "物料规格", property: "mtrlmode"},
                    {label: "单位", property: "unit", width: screen.width * 0.2},
                    {label: "数量", property: "uqty",type: "number", width: screen.width * 0.2,editable:true}];
                    
                var result2 = [
                    {label: "单价", property: "fprice",type: "number", width: screen.width * 0.2,editable:true},
                    {label: "备注", property: "mxdscrp",editable:true},
                    {label: "配置", property: "status"},
                    {label: "配置一", property: "woodcode"},
                    {label: "配置二", property: "pcode"},
                    {label: "产品批号", property: "mtrlcuscode",editable:true},
                    {label: "批号", property: "plancode",editable:true}];

                if(this.ware.iflocation > 0){
                    result = result.concat([{label: "仓位", property: "location", textColor:"#2196f3", sloteditable:true}])
                }
                result.push.apply(result, result2);

                if(this.batchEditing){
                    result.unshift({
                        property: "checked",
                        label: "选",
                        type: "selection",
                        editable: true,
                        width: 70,
                        fixed: true
                    })
                }
                
                this.gridColumns = result; 

                // this.buildGridButtonMenu()
            },
            // storageChange(){
            //     this.ware.Listmx.forEach(element => {
            //         element.location = '请选择仓位';
            //     });
            // },
            // handleMainActionRowClick(eventData) {
            //     var self = this;

            //     if (eventData.field === "storagename") {
            //         $lj.removeEventListener("storage_select");
            //         $lj.addEventListener("storage_select", function (ret) {
            //             if (ret.value) {
            //                 self.$set(self.ware, "storageid", ret.value.storageid);
            //                 self.$set(self.ware, "storagename", ret.value.storagename);
            //                 self.$set(self.ware, "outtype", ret.value.outtype);
            //                 self.$set(self.ware, "uselocation", ret.value.uselocation);
            //                 self.$set(self.ware, "iflocation", ret.value.iflocation);
            //             }
            //             self.storageChange();
            //             self.setGridColumns();
            //         });
            //         $lj.openWin("storage", {winMode: "single-select"});
            //     }

            //     if (eventData.field === "wrkGrpName") {
            //         $lj.removeEventListener("wkp_select");
            //         $lj.addEventListener("wkp_select", function (ret) {
            //             if (ret.value) {
            //                 self.$set(self.ware, "relid", ret.value.wrkGrpid);
            //                 self.$set(self.ware, "wrkGrpName", ret.value.wrkGrpName);
            //             }
            //         });
            //         $lj.openWin("wkp", {winMode: "single-select"});
            //     }
                
            // },
            handleConfirmConfig(data){
                let str = "";
                str = data == '' ? '请选择' : data;
                
                //this.ware.Listmx[this.editRowIndex].location = str;
                this.$set(this.ware.Listmx[this.editRowIndex], this.editProperty, str);
                this.editRowIndex = 0;
            },
            // handleMainRowButtonClick(eventData){
            //     var self = this;
            // },        
            // handleGridCellClick({column, row, index}) {
            //     let self = this;

            //     if (row.checked) {
            //         this.selectedItems.push(row);
            //     } else {
            //         let itemsTemp = [];
            //         for (let item of this.selectedItems) {
            //             if (item !== row) {
            //                 itemsTemp.push(item);
            //             }
            //         }
            //         this.selectedItems = itemsTemp;
            //     }

            //     if (column.editable) {
            //         return;
            //     }
                
            //     if (column.property == "location") {
            //         this.mtrlMsg.mtrlid = row.mtrlid;
            //         this.locaBasicMsg.storageid = this.ware.storageid;
            //         this.locaBasicMsg.planqty = row.uqty;
            //         this.locaBasicMsg.location_str = row.location == "请选择仓位" ? "" : row.location;
            //         console.log(' this.mtrlMsg :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.mtrlMsg));
            //         $lj.removeEventListener("storage-loca");
            //         $lj.addEventListener("storage-loca", function (ret) {
            //             console.log('？？？？反馈回调~~~~~ ret:>>！！！！！！！！！！ ', JSON.stringify(ret.value));
            //             if (ret.value) {
            //                 if (ret.value.hasOwnProperty('locaList') && ret.value.locaList.locacode) {
            //                     row.location = ret.value.locaList.locacode;
            //                 } else if (ret.value.hasOwnProperty('location_str')) {
            //                     let str = ret.value.location_str == "" ? "请选择仓位" : ret.value.location_str;
            //                     row.location = str;
            //                     // row.uqty = ret.value.sum;
            //                     self.$set(row, "uqty", ret.value.sum);
            //                 } else {
            //                     row.location = '请选择仓位'
            //                 }
            //             }
            //         });
            //         // 仓位单选
            //         $lj.openWin("storage-loca", {
            //             winMode: "single-loca",
            //             model: "newloca",
            //             queryParams: {
            //                 editState: true,
            //                 locationStr: this.locaBasicMsg.location_str,
            //                 waretype: 1,
            //                 planqty: this.locaBasicMsg.planqty, 
            //                 mtrlMsg: this.mtrlMsg,
            //                 storageid: this.locaBasicMsg.storageid
            //             }
            //         });
            //     }

            //     if(column.property == "status" || column.property == "woodcode" || column.property == "pcode"){

            //         this.locaBasicMsg.mtrlcode = row.mtrlcode;
            //         this.locaBasicMsg.mtrlname = row.mtrlname;
            //         this.locaBasicMsg.pz = row[column.property];
            //         this.configState = true;

            //         let typeid = 0;
            //         switch (column.property) {
            //             case 'status':
            //                 typeid = row.statustype;
            //                 break;
            //             case 'woodcode':
            //                 typeid = row.woodcodetype;
            //                 break;
            //             case 'pcode':
            //                 typeid = row.pcodetype;
            //                 break;
            //             default:
            //                 typeid = 0;
            //                 break;
            //         }

            //         this.editProperty = column.property;
            //         let token = $lj.getStorage("token");
            //         if(!token) return;
            //         $lj.postLJRequest("GetL1APPMtrlConfig", {
            //             token: token,
            //             typeid: typeid
            //         }, function (ret) {
            //             self.configState = true;
            //             self.$nextTick(() => {
            //                 self.editRowIndex = index;
            //                 self.$refs.useljMtrlConfig.open(ret.configureCode, ret.configureCodeMx);
            //             })
            //         });                           
            //     }
                

            // },
            handleScan(){

            },
            handleIconClick(eventData){
                
            },
            handleSubmit(){
                //DONE:提交保存
                var self = this;
                var record = this.ware;
                this.$refs.routeForm.validate().then(() => {
                    this.Save(record);
                }).catch((failed) => {
                    let msg = ""
                    switch (failed[0].name) {
                        case 'code':
                            msg = "步骤编码：" + failed[0].message
                            break;
                        case 'routestr':
                            msg = "步骤名称：" + failed[0].message
                            break;
                        default:
                            break;
                    }
                    this.$toast.fail(msg)
                });
            },
            Save(record){
                let self = this;
                $lj.postLJRequest("SaveL1Route", {
                    token: $lj.getStorage("token"),
                    route: record,
                }, function (ret) {
                    $lj.toast("保存成功！", 2000);
                    $lj.closeWin();
                    if (self.winType == 0) {
                        $lj.sendEvent("route_refresh");
                    }
                    else {
                        $lj.sendEvent("feedback_refresh");
                    }
                })
            },   
            handleAddMx(code) {
                let self = this;
                var reList = [];
                let printid = this.ware.Listmx.length;
                if(this.ware.storageid == 0 || this.ware.storageid == undefined){
                    alert("请先选择仓库");
                    return;
                }

                if(this.ware.relid == 0 || this.ware.relid == undefined){
                    alert("请先选择车间");
                    return;
                }

                if(this.iforder){
                    $lj.removeEventListener("orderml_select");
                    $lj.addEventListener("orderml_select", function (ret) {
                        if (ret.value.selectedItems) {
                            ret.value.selectedItems.forEach((item) => {
                                printid++;
                                var item = {
                                    printid:printid,
                                    mtrlid:item.mtrlid,
                                    mtrlcode:item.mtrlcode,
                                    mtrlname:item.mtrlname,
                                    mtrlmode:item.mtrlmode,
                                    relid:item.OrderID,
                                    pordercode:item.OrderCode,
                                    unit:item.unit,
                                    dscrp:'',
                                    status:item.status_mode,
                                    woodcode:item.woodcode,
                                    pcode:item.pcode,
                                    mtrlcuscode:'',
                                    fprice:0,
                                    location:'请选择仓位',
                                    uqty: item.nocmpqty
                                }                          
                                reList.push(item);
                            })

                            self.ware.Listmx = self.ware.Listmx.concat(reList);
                        }
                    })

                    $lj.openWin("orderml-selection", {winMode: "multi-select",wrkGrpid:this.ware.relid});
                }
                else{
                    $lj.removeEventListener("mtrldef_select");
                    $lj.addEventListener("mtrldef_select", function (ret) {
                        if (ret.value.selectedItems) {
                            ret.value.selectedItems.forEach((item) => {
                                printid++;
                                var item = {
                                    printid:printid,
                                    mtrlid:item.mtrlid,
                                    mtrlcode:item.mtrlcode,
                                    mtrlname:item.mtrlname,
                                    mtrlmode:item.mtrlmode,
                                    unit:item.unit,
                                    dscrp:'',
                                    status:'请选择',
                                    woodcode:'请选择',
                                    pcode:'请选择',
                                    mtrlcuscode:'',
                                    fprice:0,
                                    location:'请选择仓位'
                                }                          
                                reList.push(item);
                            })

                            self.ware.Listmx = self.ware.Listmx.concat(reList);
                        }
                    })

                    $lj.openWin('mtrldef', {winMode:"multi-select"});
                }
            },
            cleanMx() {
                this.ware.Listmx = [];
            },
            setRowStyle(rowIndex, row) {
                if (row.checkStorage) {
                    return {
                        backgroundColor: 'rgba(252, 78, 44, 0.1)',
                        height: '32px'
                    }
                } else {
                    return {
                        height:'32px'
                    }
                }
            },
        },
        computed: {
            dictColumns(){
                let result = [];
                // if(this.winType == 0){
                    result = [
                        {label: "路线编号", property: "routecode",},
                        {label: "路线名称", property: "routename",},
                        {label: "路线说明", property: "dscrp", type: "TextArea",style: "height: auto;"},
                    ];
                // }
                // else{
                //     result = [
                //         {label: "路线编号", property: "routecode",},
                //         {label: "路线名称", property: "routename",},
                //         {label: "路线说明", property: "dscrp", type: "TextArea", style: "height: auto;"},
                //     ];
                // }

                return result;
            },
            mainButtons() {
                let buttons = [
                    {icon:"icon-ic_add",color:"primary",span:3,label:"明细",isIconLeft:true,methodName:"add",visiable:!this.batchEditing},
                    {icon: this.iforder ? "icon-kongjianyixuan" : "icon-kongjianweixuan",span:5,label:"明细按计划",isIconLeft:true,methodName:"plan",visiable:!this.batchEditing},
                    {icon:"icon-settings",color:"primary",span:4,label:"批设置",methodName:"batchSetting",visiable:!this.batchEditing,isIconLeft:true},
                    {color:"primary",span:2,label:this.selectedItems.length > 0 ? "反选" : "全选",isIconLeft:true,methodName:"allcheck",visiable:this.batchEditing},
                    {icon:"icon-close",color:"primary",span:3,label:"删除",isIconLeft:true,methodName:"delete",visiable:this.batchEditing},
                    {color:"primary",span:2,label:this.selectedItems.length > 0 ? "完成" : "退出",isIconLeft:true,methodName:"finish",offset:5,visiable:this.batchEditing}
                ]
                return buttons;
            },
            moreButtons() {
                let buttons = [
                    {icon:"icon-ic_refresh",color:"grey",label:"清空",methodName:"clean",visiable:!this.batchEditing},
                    {icon:"icon-settings",color:"grey",label:"布局",methodName:"setting",visiable:true},
                ]
                return buttons;
            }
        }
    }
</script>

<style lang="less">
.background-color {
    .content {
        padding-bottom: 24px;
    }
}
.save-tag{
    text-align: center; // 文本居中 
    position: absolute; // 绝对定位
    bottom: 8px;
    font-weight: bold;
    right: -20px;
    width: 80px;
    font-size: 12px;
    height: 20px;
    line-height: 20px;
    transform: rotate(-40deg);
    opacity: 0.4;
    z-index: 10;
    background-color: #F9D5DD;
    color: #FF4E4E;
} 

.cell-group-filter {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 0;
    top: -5px;

    .iconfont {
        font-size: 12px!important;
    }
    .van-button {
        height: 26px;
        line-height: 26px;
        color: @light-label-primary;
        background-color: @light-fill-quarternary;
    }
}
</style>