<template>
    <div>
        <lj-win-common :title="title" :show-back="true" :closeWinHandler = "handleCloseWin">
            <template slot="header_right">
                <mu-button icon @click="openSettingWin">
                    <i class="iconfont icon-settings"></i>
                </mu-button>
                <mu-menu placement="bottom-end" :open.sync="openTitle">
                    <mu-button icon>
                        <i class="iconfont icon-more"></i>
                    </mu-button>
                    <mu-list slot="content">
                        <mu-list-item button @click="handleBomDetail">
                            <mu-list-item-title>用料详情</mu-list-item-title>
                        </mu-list-item>
                        <mu-list-item button @click="handleGotoMtrldef">
                            <mu-list-item-title>物料详情</mu-list-item-title>
                        </mu-list-item>
                    </mu-list>
                </mu-menu>
            </template>
            <div slot="body">
                <template>
                    <div class="lj-card-item">
                        <mu-row>
                            <mu-col span="3" class="lj-card-secondary-title">质检单号：</mu-col>
                            <mu-col span="7" class="lj-card-secondary-content">{{mainObject.billcode}}</mu-col>
                            <mu-col span="2">
                                <lj-status-badge :value="getStatus(mainObject.flag,mainObject.SecFlag,mainObject.saveflag,mainObject.ifspecial,mainObject.buyerAuditflag)"
                                                 :statusDic="statusDic"/>
                            </mu-col>
                            <mu-col span="3" class="lj-card-secondary-title">送检号：</mu-col>
                            <mu-col span="9" class="lj-card-secondary-content">{{mainObject.relcode}}</mu-col>
                            <mu-col span="3" class="lj-card-secondary-title">物料名称：</mu-col>
                            <mu-col span="9" class="lj-card-secondary-content">{{mainObject.mtrlname}}</mu-col>
                            <mu-col span="3" class="lj-card-secondary-title">物料编码：</mu-col>
                            <mu-col span="9" class="lj-card-secondary-content">{{mainObject.mtrlcode}}</mu-col>
                            <mu-col span="3" class="lj-card-secondary-title">物料规格：</mu-col>
                            <mu-col span="9" class="lj-card-secondary-content">{{mainObject.mtrlmode}}</mu-col>
                            <mu-col span="3" class="lj-card-secondary-title">检验日期：</mu-col>
                            <mu-col span="9" class="lj-card-secondary-content">{{mainObject.checkdate|dateFilter}}
                            </mu-col>
                            <mu-col span="3" class="lj-card-secondary-title" :class="{ 'lj-grid-editable-cell' : ifedit }">检验类型：</mu-col>
                            <mu-col span="4" class="lj-card-secondary-content" :class="{ 'lj-grid-editable-cell' : ifedit }">
                                &nbsp;<input type="radio" :disabled="!ifedit" v-model="mainObject.checktype" value="1" @change="handleChecktypeChange">全检
                                &nbsp;<input type="radio" :disabled="!ifedit" v-model="mainObject.checktype" value="0" @change="handleChecktypeChange">抽检
                            </mu-col>
                            <mu-col span="3" class="lj-card-secondary-title" :class="{ 'lj-grid-editable-cell' : ifedit }">检验数：</mu-col>
                            <mu-col span="2" class="lj-card-secondary-content">
                                <input type="text" :class="{ 'lj-grid-editable-cell' : ifedit }" style="width: 60px;height: 25px;"
                                       :disabled="ifCheckAll" oninput="value=value.replace(/[^\d]/g,'')"
                                       v-on:input="handleCheckQtyChange" v-model="mainObject.checkqty" />
                            </mu-col>
                            <mu-col span="3" class="lj-card-secondary-title">批量：</mu-col>
                            <mu-col span="2" class="lj-card-secondary-content">{{mainObject.qty}}</mu-col>
                            <mu-col span="4" class="lj-card-secondary-title">总不合格数：</mu-col>
                            <mu-col span="3" class="lj-card-secondary-content">{{allbadqty}}</mu-col>
                            <mu-col span="4" class="lj-card-secondary-title">当前合格率：</mu-col>
                            <mu-col span="8" class="lj-card-secondary-content">{{goodRate}}%</mu-col>
                            <template v-if="!ifCheckAll">
                                <mu-col span="4" class="lj-card-secondary-title lj-grid-editable-cell">推荐合格率：</mu-col>
                                <mu-col span="8" class="lj-card-secondary-content">90%</mu-col>
                            </template>
                            <mu-col span="3" class="lj-card-secondary-title">备注：</mu-col>
                            <mu-col span="9" class="lj-card-secondary-content">{{mainObject.dscrp}}</mu-col>
                            <mu-col span="3" class="lj-card-secondary-title" :class="{ 'lj-grid-editable-cell' : ifedit }">异常原因：</mu-col>
                            <mu-col span="9" class="lj-card-secondary-content">
                                <mu-auto-complete
                                    v-model="mainObject.reson"
                                    :placeholder="ifedit ? '请输入异常原因' : ''"
                                    ref="reasonField"
                                    :data="cpCheckMxReasonHistory"
                                    openOnFocus
                                    solo
                                    full-width
                                    @select="reasonSelected"
                                    :disabled="!ifedit"
                                >
                                </mu-auto-complete>
                            </mu-col>
                            <mu-col span="3" class="lj-card-secondary-title" :class="{ 'lj-grid-editable-cell' : ifedit }">处理建议：</mu-col>
                            <mu-col span="9" class="lj-card-secondary-content">
                                <mu-auto-complete
                                    v-model="mainObject.suggest"
                                    :placeholder="ifedit ? '请输入处理建议' : ''"
                                    ref="suggestField"
                                    :data="cpCheckMxSuggestHistory"
                                    openOnFocus
                                    solo
                                    full-width
                                    @select="suggestSelected"
                                    :disabled="!ifedit"
                                >
                                </mu-auto-complete>
                            </mu-col>
                        </mu-row>
                    </div>

                    <div class="lj-card-item">
                        <mu-row>
                            <mu-col span="3" class="lj-card-secondary-title">客户要求：</mu-col>
                            <mu-col span="9" class="lj-card-secondary-content">{{mainObject.dscrpSum}}</mu-col>
                            <mu-col span="3" class="lj-card-secondary-title">特殊要求：</mu-col>
                            <mu-col span="9" class="lj-card-secondary-content" >
                                <a @click="specialDialogOpen=true">点击查看</a>
                            </mu-col>
                        </mu-row>
                    </div>
                </template>
                <template>
                    <lj-grid :table-data="mxList" :columns="displayColumns" :editing="ifedit"
                             @content-cell-change="handleBadQtyChange"
                             @cell-click="handleGridCellClick"/>
                </template>
                <template>
                    <div class="lj-card-item">
                        <mu-row>
                            <mu-col span="4" class="lj-card-secondary-title" style="text-align: center;" v-for="(picture, index) in pictureList" ::key="index">
                                <lj-img style="width: 30vw; height: 30vw;" v-bind:src="picture.url" v-bind:md5="picture.filemd5" @click.native="photoBrowser(index)"/><br>
                                {{picture.fileName}}
                            </mu-col>
                        </mu-row>
                    </div>
                </template>
            </div>
            <template v-if="ifedit" slot="footer">
                <mu-row>
                    <mu-col tag="mu-button" @click.native="handleSave(0)">临时保存</mu-col>
                    <!-- <template v-if="ifCheckAll">
                        <mu-col tag="mu-button" color="primary" @click.native="handleSave(1)">保存并审核</mu-col>
                    </template> -->
                    <template>
                        <mu-col tag="mu-button" color="primary" @click.native="handleSave(1)">合格</mu-col>
                        <mu-col tag="mu-button" color="error" @click.native="handleSave(2)">不合格</mu-col>
                    </template>
                </mu-row>
            </template>
        </lj-win-common>
        <mu-dialog :open.sync="mxDialogOpen" title="质检明细标准" scrollable>
            {{currentMxItem.Standard? currentMxItem.Standard:"该质检明细未设置标准"}}
            <mu-button slot="actions" color="primary" flat @click="mxDialogOpen=false">
                关闭
            </mu-button>
        </mu-dialog>
        <mu-dialog :open.sync="specialDialogOpen" width="100%" title="客户产品特殊要求" scrollable>
            {{mainObject.specialcontent}}
            <div class="lj-card-item">
                <mu-row>
                    <mu-col span="4" class="lj-card-secondary-title"
                            style="text-align: center; padding-bottom: 8px;"
                            v-for="(picture, index) in specialFiles" :key="index">
                        <lj-img style="width: 25vw; height: 25vw;" :src="picture.url"
                                :md5="picture.filemd5" @click.native="specialPhotoBrowser(index)"/>
                        <br>
                    </mu-col>
                </mu-row>
            </div>
            <mu-button slot="actions" color="primary" flat @click="specialDialogOpen=false">
                关闭
            </mu-button>
        </mu-dialog>
    </div>

</template>

<script>
    import ljWinCommon from 'components/lj-win-common'
    import LjStatusBadge from "components/lj-status-badge";
    import LjGrid from "components/lj-grid";
    import LjImg from "components/lj-img"

    export default {
        name: "cpcheck-mx",
        components: {
            ljWinCommon,
            LjStatusBadge,
            LjGrid,
            LjImg
        },
        created() {
            var pageParm = $lj.getPageParam();
            this.mainObject = pageParm.mainObject;
            this.allbadqty = this.mainObject.badqty;
            this.mainObject.badinqty = 0;
            this.goodRate = Math.round((Number(this.mainObject.checkqty) - Number(this.allbadqty))  * 100 / Number(this.mainObject.checkqty));
            if (this.mainObject.flag == 0 && this.mainObject.SecFlag == 0) {
                this.ifedit = true;
            }
            if (!this.ifedit) {
                this.gridColumns[3].editable = false;
                this.gridColumns[4].editable = false;
            }

            this.getReasonHistory();
            this.getSuggestHistory();

            this.MergeCustomSetting();
        },
        mounted() {
            this.ifCheckAll = (!this.ifedit || this.mainObject.checktype == 1) ? true : false;
            var self = this;
            $lj.postLJRequest("GetL1CpcheckMx", {
                token: $lj.getStorage("token"),
                billid: this.mainObject.billid
            }, function (rsp) {
                if (rsp) {
                    for (const cpcheckmx of rsp.cpcheckmxList) {
                        let mx = cpcheckmx;
                        if (cpcheckmx.resultstr !== '') {
                            let resultArr = cpcheckmx.resultstr.split(';');
                            if (resultArr.length > 0) {
                                for(let i = 0; i < resultArr.length; i++) {
                                    self.$set(mx, 'QcResult' + (i + 1), resultArr[i]);
                                }
                            }
                        }
                        self.mxList.push(mx)
                        for (const file of cpcheckmx.fileList) {
                            self.pictureList.push(file);
                        }
                    }
                    self.pictureList.sort(self.comparePicutre("relidmx"))
                    self.handleChecktypeChange();
                    self.handleBadQtyChange();
                    self.getCustProspecialItem();
                }
            })
        },
        data() {
            return {
                winmode: 0,
                pictureList: [],
                goodRate: 100,
                ifedit: false,
                ifCheckAll: true,
                mxDialogOpen: false,
                currentMxItem: {},
                allbadqty: 0,
                mainObject: {},
                mxList: [],
                gridColumns: [{label: "序", property: "printid", width: screen.width * 0.1},
                    {label: "检验项目", property: "checkitem_itemname", width: screen.width * 0.2},
                    {label: "标准", property: "picHelp", icon: "iconfont icon-help1", width: screen.width * 0.1 , type: "pic"},
                    {label: "不合格数", property: "badqty", width: screen.width * 0.2, type: "number", editable: true},
                    {label: "质检结果", property: "QcResult", width: screen.width * 0.3, editable: true},
                    {label: "", property: "picPhoto", icon: "iconfont icon-camera1", width: screen.width * 0.1 , type: "pic"}
                ],
                statusDic: {
                    "待质检": {color: "Warn"},
                    "待初审": {color: "Alert"},
                    "待采购审": {color: "Alert"},
                    "待二审": {color: "Normal"},
                    "已完成": {color: "Pass"}
                },
                specialDialogOpen: false,
                specialFiles: [],
                ifmulti: false,
                cpCheckMxReasonHistory: [],
                cpCheckMxSuggestHistory: [],
                capacity: 10,
                draftName: "cpCheckWWMxReasonHistory",
                suggestDraftName: "cpCheckWWMxSuggestHistory",
                apiName: 'cpCheckWWMx',
                dwname: "L1APP",
                openTitle: false, // 打开右上角菜单
                displayColumns: []
            }
        },
        methods: {
            saveReason() {
                if(!this.mainObject.reson) return;
                this._cacheSet(this.cpCheckMxReasonHistory,this.mainObject.reson);
                // 保存记录
                $lj.setStorage(this.draftName, this.cpCheckMxReasonHistory);
            },
            saveSuggest() {
                if(!this.mainObject.suggest) return;
                this._cacheSet(this.cpCheckMxSuggestHistory,this.mainObject.suggest);
                // 保存记录
                $lj.setStorage(this.suggestDraftName, this.cpCheckMxSuggestHistory);
            },
            // 登录历史
            getReasonHistory() {
                this.cpCheckMxReasonHistory = $lj.getStorage(this.draftName) || [];
                console.log('$lj.this.userHistoryAccount("userHistoryAccount")>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> :>> ', JSON.stringify(this.cpCheckMxReasonHistory));
            },
            // 登录历史
            getSuggestHistory() {
                this.cpCheckMxSuggestHistory = $lj.getStorage(this.suggestDraftName) || [];
                console.log('$lj.this.userHistoryAccount("userHistoryAccount")>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> :>> ', JSON.stringify(this.cpCheckMxSuggestHistory));
            },
            reasonSelected(item, index) {
                // console.log("reasonSelected item",JSON.stringify(item),"index ====>",index);
                // console.log('reasonSelected this.maxUserHistoryAccount :>> ', JSON.stringify(this.maxUserHistoryAccount));
                this.mainObject.reson = this._cacheGet(this.cpCheckMxReasonHistory,item);
                this.$refs.reasonField.blur();
            },
            suggestSelected(item, index) {
                // console.log("reasonSelected item",JSON.stringify(item),"index ====>",index);
                // console.log('reasonSelected this.maxUserHistoryAccount :>> ', JSON.stringify(this.maxUserHistoryAccount));
                this.mainObject.suggest = this._cacheGet(this.cpCheckMxSuggestHistory,item);
                this.$refs.suggestField.blur();
            },
            /** LRU */
            _cacheGet(arr,key) {
                let index = arr.findIndex((item) => item === key);
                if (index === -1) {
                    return -1;
                }
                // 删除此元素后插入到数组第一项
                let value = arr[index];
                arr.splice(index, 1);
                arr.unshift(value);
                return value;
            },
            _cacheSet(arr,key) {
                let index = arr.findIndex((item) => item === key);
                // 想要插入的数据已经存在了，那么直接提升它就可以
                if (index > -1) {
                    arr.splice(index, 1);
                } else if (arr.length >= this.capacity) {
                    // 若已经到达最大限制，先淘汰一个最久没有使用的
                    arr.pop();
                }
                arr.unshift(key);
            },
            handleCloseWin(){
                if (this.ifedit){
                    $lj.confirm('提示', '是否放弃保存？', function () {
                        $lj.closeWin();
                    });
                } else {
                    $lj.closeWin();
                }
                this.saveReason();
                this.saveSuggest();
            },
            handleSave(type) {
                var savetype = type;
                this.mainObject.badqty = this.allbadqty;
                if(Number(this.mainObject.checkqty) <= 0) {
                    alert("错误的抽检数");
                    return;
                }
                if (Number(this.mainObject.qty) < Number(this.mainObject.checkqty)) {
                    alert("检验数数不能大于批量");
                    return;
                }
                if (Number(this.mainObject.checkqty) < Number(this.mainObject.badqty)) {
                    alert("总不合格数不能大于检验数");
                    return;
                }
                //主表数据
                if (this.ifCheckAll) {
                    this.mainObject.goodqty = Number(this.mainObject.qty) - Number(this.mainObject.badqty);
                } else {
                    this.mainObject.goodqty = Number(this.mainObject.checkqty) - Number(this.mainObject.badqty);
                }
                let requestBody = {
                    token: $lj.getStorage("token"),
                    savetype: savetype,
                    cpcheck: this.mainObject,
                    cpcheckmxList: this.mxList,
                    cpcheckmxFjList: this.pictureList,
                    ifMultiResult: this.ifmulti ? 1 : 0,
                };
                $lj.postLJRequest("CpcheckzzL1Save", requestBody, function (rsp) {
                    if (rsp) {
                        $lj.toast("保存成功！", 2000);
                        $lj.sendEvent("cpcheck_refresh");
                        $lj.closeWin();
                    }
                })

                this.saveReason();
                this.saveSuggest();
            },
            handleGridCellClick({column, row, index}) {
                if (!column) {
                    return;
                }
                if (column.editable) {
                    return;
                }
                if (column.property === "picHelp") {
                    this.currentMxItem = row;
                    this.mxDialogOpen = true;
                }
                else if(column.property == "picPhoto"){
                    if(!this.ifedit){
                        return;
                    }
                    var self = this;
                    $lj.getPicture(function(ret){
                        if (ret.data){
                            var picture = {
                                url : ret.data,
                                relidmx : row.printid,
                                fileName : row.checkitem_itemname,
                                base64 : ret.base64Data,
                                fileType : "." + ret.data.substring(ret.data.lastIndexOf("\/") + 1, ret.data.length).split(".")[1],
                                ifDBSave : 0
                            };
                            var i = 0;
                            for (const pic of self.pictureList){
                                if (pic.relidmx == picture.relidmx){
                                    if(pic.base64 == picture.base64){
                                        $lj.toast("图片已添加过，不能重复添加", 2000);
                                        return;
                                    }
                                    i++;
                                }
                            }
                            if (i >= 6){
                                alert("检查项目:" + row.checkitem_itemname + "图片数不能超过6张！");
                                return;
                            }
                            self.pictureList.push(picture);
                            self.pictureList.sort(self.comparePicutre("relidmx")); //排序
                        }
                    })
                }
            },
            handleBadQtyChange(event) {
                if (!event) {
                    return;
                }
                let {row, column} = event;
                if (!row || !column) {
                    return;
                }
                if (column.property !== 'badqty') {
                    return;
                }
                var allbadqty = 0;
                for (var i in this.mxList) {
                    this.mxList[i].badqty = Number(this.mxList[i].badqty);
                    allbadqty += this.mxList[i].badqty;
                }
                this.allbadqty = allbadqty;
                this.goodRate = Math.round((Number(this.mainObject.checkqty) - Number(this.allbadqty))  * 100 / Number(this.mainObject.checkqty));
            },
            getStatus(flag,secflag,saveflag,ifspecial,buyerAuditflag){
                if (saveflag == 0 && flag == 0 && secflag == 0){
                    return "待质检";
                }
                if (flag == 0){
                    return "待初审";
                }
                if (secflag == 0){
                    return "待二审";
                }
                return "已完成";
            },
            handleChecktypeChange() {
                this.ifCheckAll = this.mainObject.checktype == 1 ? true : false;
                if (this.ifCheckAll) {
                    this.mainObject.checkqty = this.mainObject.qty;
                }
                this.goodRate = Math.round((Number(this.mainObject.checkqty) - Number(this.allbadqty))  * 100 / Number(this.mainObject.checkqty));
            },
            handleCheckQtyChange() {
                this.mainObject.checkqty = Number(this.mainObject.checkqty) > Number(this.mainObject.qty) ? Number(this.mainObject.qty) : Number(this.mainObject.checkqty);
                if(Number(this.mainObject.checkqty) == 0){
                    this.goodRate = 0;
                    return;
                }
                this.goodRate = Math.round((Number(this.mainObject.checkqty) - Number(this.allbadqty))  * 100 / Number(this.mainObject.checkqty));
            },
            comparePicutre(propertyName) {
                return function(object1, object2) {
                    var value1 = object1[propertyName];
                    var value2 = object2[propertyName];
                    if (value2 > value1) {
                        return -1;
                    } else if (value2 < value1) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            },
            photoBrowser(index){
                var images = [];
                for (const picture of this.pictureList) {
                    if(picture.ifDBSave === 0){
                        images.push(picture.url);
                    }else{
                        var url = $lj.constant.cacheDir + "/" + picture.filemd5;
                        images.push(url);
                    }
                }
                $lj.photoBrowser(images, index);
            },
            handleBomDetail() {
                $lj.openWin("mtrl-use-detail", {orderid: this.mainObject.orderid});
                this.openTitle = false;
            },
            /**
             * @description 查看看物料详情
             */
             handleGotoMtrldef() {
                $lj.openWin("mtrldef-fj", {mainObject: this.mainObject});
                this.openTitle = false;
            },
            getCustProspecialItem() {
                var self = this;
                $lj.postLJRequest("GetCustProspecialItem", {
                    token: $lj.getStorage("token"),
                    cusid: this.mainObject.cusid,
                    mtrlid: this.mainObject.mtrlid
                }, function (ret) {
                    self.specialFiles = ret.specialitem.files
                })
            },
            openSettingWin(){
                let self = this;
                $lj.removeEventListener("grid_style_updated");
                $lj.addEventListener("grid_style_updated", function (ret) {
                    if (ret.value) {
                        if (ret.value.dwname === self.dwname && ret.value.itemname === self.apiName) {
                            self.MergeCustomSetting();
                        }
                    }
                });
                $lj.openWin('grid-drag-setting', {
                    columns: this.gridColumns,
                    apiName: this.apiName
                });
            },
            MergeCustomSetting: function () {
                let userInfo = $lj.getStorage('userInfo');
                let empid = userInfo.empid;
                let requestBody = {
                    token: $lj.getStorage("token"),
                    empid: empid,
                    dwname: this.dwname,
                    itemname: this.apiName,
                    ifcompress: 1
                };
                let self = this;
                self.displayColumns = [];
                this.popupColumns = [];
                $lj.postLJRequest(
                    "GetSysUserFileString", requestBody,
                    function (ret) {
                        if (ret && ret.itemvalue) {
                            let customSetting = JSON.parse(ret.itemvalue);
                            // 构建field-style键值对
                            let customSettingDictionary = new Map();
                            for (let item of customSetting) {
                                customSettingDictionary.set(item.property, item);
                            }
                            // 合并过滤字段，以这个字典为准，用户历史设置多删少补
                            for (let item of self.gridColumns) {
                                let curField = item.property;
                                let userStyle = customSettingDictionary.get(curField);
                                if (userStyle) {
                                    // for (let prop in userStyle) {
                                    //     item[prop] = userStyle[prop];
                                    // }
                                    item.order = userStyle.order;
                                    item.invisible = userStyle.invisible;
                                } else {
                                    // 新增字段，暂不显示
                                    item.invisible = true;
                                }
                            }
                        } else {
                            for (let i in self.gridColumns) {
                                self.gridColumns[i].order = i;
                            }
                        }
                        self.gridColumns.sort(function (object1, object2) {
                            return object1.order - object2.order;
                        });
                        for (let i in self.gridColumns) {
                            let item = self.gridColumns[i];
                            item.order = i;
                            if (item.optionid) {
                                let optionName = $lj.getOptionValue(item.optionid);
                                item.label = optionName ? optionName : item.label;
                            }
                            self.displayColumns.push(item);
                        }
                        if (self.popupColumns.length > 0) {
                            self.displayColumns.push(self.moreColumn);
                        }
                    }
                );
            },
        },
        computed: {
            title() {
                if(this.ifedit){
                    return "委外质检单-编辑";
                }else{
                    return "委外质检单-明细";
                }
            }
        },
        filters: {
            checkTypeFormat(checktype) {
                switch (checktype) {
                    case 0:
                        return "抽检";
                    case 1:
                        return "全检";
                }
            }
        }
    }
</script>
<style>
.mu-input.is-solo{
    padding: 0;
}
.mu-input {
    font-size: 14px;
    min-height: 1px;
}
.mu-text-field-input {
    height: auto;
    color: #2196F3;
}
</style>
