<template>
    <div class="ele-body">
        <el-card shadow="never" v-loading="loading">
            <produceOrder-search @search="reload" ref="searchRef" :statusOpt="statusOpt" :planType="planType"
                :activeName="activeName">
            </produceOrder-search>

            <!-- 数据表格 -->
            <ele-pro-table ref="table" :key="activeName" :initLoad="false" :columns="newColumns"
                :datasource="datasource" row-key="code" :cache-key="`${activeName}produceOrderTable`"
                :selection.sync="selection" @sort-change="onSortChange" autoAmendPage :parse-data="parseData">


                <template v-slot:code="{ row }">
                    <el-link type="primary" :underline="false" @click="goDetail(row)">
                        {{ row.code }}
                    </el-link>
                </template>

                <template v-slot:QRcode="{ row }">
                    <el-link type="primary" :underline="false" @click="handleQRcode(row)">生成二维码
                    </el-link>
                </template>

                <template v-slot:priority="{ row }">
                    <div style="display: flex">
                        <el-input v-model="row.priority" type="number" size="mini" :min="0" :max="10"
                            @change="priorityChange(row)" style="width: 80px"></el-input>
                        <el-popover placement="right" width="200" trigger="hover"
                            content="数值越大优先级越高（0-3普通, 4-6优先, 7-10紧急）">
                            <div class="sort-wrap" slot="reference">
                                <i class="el-icon-caret-top" @click="sortTop(row)"></i>
                                <i class="el-icon-caret-bottom" @click="sortBottom(row)"></i>
                            </div>
                        </el-popover>
                    </div>
                </template>

                <template v-slot:formingNum="{ row }">
                    <span> {{ row.formingNum }} {{ row.unit }} </span>
                </template>

                <template v-slot:formingWeight="{ row }">
                    <span> {{ row.formingNum }} {{ row.weightUnit }} </span>
                </template>

                <template v-slot:status="{ row }">
                    <span :class="{ 'ele-text-danger': row.status == 3 }">
                        {{ statusFormatter(row.status) }}
                    </span>
                </template>
                <!-- 操作列 -->
                <template v-slot:action="{ row }">
                    <template>
                        <el-link type="primary" :underline="false" @click="goDetail(row)">
                            领料/投料/报工
                        </el-link>
                    </template>
                </template>
            </ele-pro-table>
        </el-card>

        <print ref="printRef"></print>
        <printSr ref="printSrRef"></printSr>
        <printTg ref="printTgRef"></printTg>

        <createDialog ref="createRef" @success="createSuccess" />
        <unpackDialog ref="unpackRef" @success="createSuccess" />
        <pickingDialog ref="PickingRef" />

        <detailsPop ref="detailsRef"> </detailsPop>
        <EquipmentDialog ref="equipmentRef" @choose="choose"></EquipmentDialog>
    </div>
</template>

<script>
import {
    getPage,
    batchCompletion,
    cancelCompletion,
    updatePriority,
    update
} from '@/api/produceOrder/index.js';
import { workorderPage } from '@/api/workOrderList'

import { fieldModel } from '@/api/produceWord/index.js';
import produceOrderSearch from './components/produceOrder-search.vue';
import createDialog from './components/createDialog.vue';
import unpackDialog from './components/unpackDialog.vue';
import pickingDialog from './components/pickingDialog.vue';
import print from './components/print.vue';
import printSr from './components/printSr';
import printTg from './components/printTg';
import EquipmentDialog from './components/EquipmentDialog.vue'
import detailsPop from './components/details/index.vue'

import { debounce } from 'lodash';


export default {
    components: {
        produceOrderSearch,
        pickingDialog,
        createDialog,
        unpackDialog,
        print,
        printSr,
        printTg,
        detailsPop,
        EquipmentDialog
    },
    data() {
        return {
            activeName: 'first',
            id: '',

            // 加载状态
            loading: false,
            pageType: 'add',
            dialogTitle: '',
            isBindPlan: false,
            statusOpt: {
                first: [
                    { label: '所有状态', value: '5,4' },
                    { label: '待生产', value: '4' },
                    { label: '生产中', value: '5' }
                    // { label: '已延期', value: '7' }
                ],
                second: [{ label: '已完成', value: '6' }]
            },
            planType: [
                { label: '所有计划类型', value: null },
                { label: '内销计划', value: '1' },
                { label: '外销计划', value: '2' },
                { label: '预制计划', value: '3' }
            ],
            selection: [],
            newColumns: []
        };
    },
    computed: {
        // 表格列配置
        columns() {
            const opt = {
                first: [
                    // {
                    //   prop: 'deliveryTime',
                    //   label: '预测交货日期',
                    //   align: 'center',
                    //   showOverflowTooltip: true,
                    //   minWidth: 110
                    // }
                ],
                second: [
                    {
                        prop: 'completeTime',
                        label: '完成时间',
                        align: 'center'
                    },
                    {
                        prop: 'cycle',
                        label: '生产周期',
                        align: 'center'
                    }
                ]
            };

            return [
                {
                    width: 45,
                    type: 'selection',
                    columnKey: 'selection',
                    align: 'center',
                    fixed: 'left'
                },

                // {
                //   prop: 'batchNo',
                //   label: '批次号',
                //   align: 'center',
                //   minWidth: 130
                // },

                {
                    slot: 'code',
                    label: '生产工单号',
                    align: 'center',
                    minWidth: 110
                },
                // {
                //   prop: 'originalCode',
                //   label: '原始工单号',
                //   align: 'center',
                //   minWidth: 110
                // },

                {
                    slot: 'QRcode',
                    label: '二维码',
                    align: 'center',
                    minWidth: 110
                },

                {
                    prop: 'productionPlanCode',
                    label: '计划编号',
                    align: 'center',
                    minWidth: 110
                },
                {
                    prop: 'planType',
                    label: '计划类型',
                    align: 'center',
                    formatter: (row) => {
                        const obj = this.planType.find((i) => i.value == row.planType);
                        return obj && obj.label;
                    }
                },
                {
                    prop: 'produceRoutingName',
                    label: '工艺路线',
                    align: 'center'
                },
                {
                    prop: 'productCode',
                    label: '编码',
                    align: 'center'
                },
                {
                    prop: 'productName',
                    label: '名称',
                    align: 'center'
                },
                {
                    prop: 'brandNo',
                    label: '牌号',
                    align: 'center'
                },
                {
                    prop: 'model',
                    label: '型号',
                    align: 'center'
                },

                // {
                //   prop: 'priority',
                //   label: '优先级',
                //   align: 'center',
                //   minWidth: 120,
                //   slot: 'priority',
                //   sortable: 'custom'
                // },

                {
                    prop: 'formingNum',
                    label: '要求生产数量',
                    align: 'center',
                    slot: 'formingNum',
                    showOverflowTooltip: true,
                    minWidth: 110
                },
                {
                    prop: 'formingWeight',
                    label: '要求生产重量',
                    slot: 'formingWeight',
                    align: 'center',
                    showOverflowTooltip: true,
                    minWidth: 110
                },
                {
                    prop: 'formedNum',
                    label: '已生产数量',
                    align: 'center',
                    showOverflowTooltip: true,
                    minWidth: 110
                },
                {
                    prop: 'formedWeight',
                    label: '已生产重量',
                    align: 'center',
                    showOverflowTooltip: true,
                    minWidth: 110
                },
                {
                    prop: 'planStartTime',
                    label: '计划开始时间',
                    align: 'center',
                    showOverflowTooltip: true,
                    minWidth: 110
                },
                {
                    prop: 'planCompleteTime',
                    label: '计划结束时间',
                    align: 'center',
                    showOverflowTooltip: true,
                    minWidth: 110
                },
                {
                    prop: 'startTime',
                    label: '实际开始时间',
                    align: 'center',
                    showOverflowTooltip: true,
                    minWidth: 110
                },

                ...opt[this.activeName],
                {
                    prop: 'createTime',
                    label: '创建时间',
                    align: 'center',
                    showOverflowTooltip: true,
                    minWidth: 110
                },
                {
                    slot: 'status',
                    label: '状态',
                    align: 'center',
                    formatter: (row) => {
                        const obj = this.statusOpt[this.activeName].find(
                            (i) => i.value == row.status
                        );
                        return obj && obj.label;
                    }
                },

                {
                    prop: 'teamName',
                    label: '班组',
                    align: 'center',
                    showOverflowTooltip: true
                }
            ];
        },

        clientEnvironmentId() {
            return this.$store.state.user.info.clientEnvironmentId;
        }
    },
    created() {
        this.getFieldModel();
    },
    methods: {
        handlePicking() {
            this.$router.push({
                path: '/produceOrder/picking'
            });
        },
        statusFormatter(status) {
            const obj = this.statusOpt[this.activeName].find(
                (i) => i.value == status
            );

            return obj && obj.label;
        },

        routing(row) {
            this.id = row.id

            this.$refs.equipmentRef.open()
        },

        /* 表格数据源 */
        async datasource({ page, limit, where, order }) {
            let res = await workorderPage({
                ...where,
                ...order,
                pageNum: page,
                size: limit,
                ...this.sort
            });
            // res['list'] = this.flattenArray(res.list)
            return res;
        },

        onSortChange(e) {
            let sort = {
                orderBy: e.order,
                sortName: e.prop
            };
            this.sort = sort;
            this.reload();
        },
        flattenArray(arr) {
            var result = []; // 存放结果的数组
            for (let i = 0; i < arr.length; i++) {
                if (Array.isArray(arr[i].subWorkOrder)) {
                    let _arr = [];
                    _arr = _arr.concat(arr[i].subWorkOrder);
                    delete arr[i].subWorkOrder;
                    result.push(arr[i]);
                    result.push(..._arr);
                } else {
                    result.push(arr[i]);
                }
            }

            return result;
        },

        /* 数据转为树形结构 */
        parseData(data) {

            return {
                ...data,
                list: this.$util.toTreeData({
                    data: data.list,
                    count: data.total,

                    idField: 'code',
                    parentIdField: 'originalCode'
                })
            };
        },

        /* 数据转为树形结构 */

        createSuccess() {
            this.reload();
        },
        handleCreate() {
            this.$refs.createRef.open(0);
        },
        // 发布工单
        handleOrderPublish(type, row) {
            this.$router.push({
                path: '/produce',
                query: {
                    workOrderId: row.id
                }
            });
        },

        getFieldModel() {

            fieldModel({ fieldModel: 't_main_category' }).then((res) => {
                const privateColumn = [
                    {
                        columnKey: 'action',
                        label: '操作',
                        width: 150,
                        align: 'center',
                        resizable: false,
                        fixed: 'right',
                        slot: 'action',
                        showOverflowTooltip: true
                    }
                ];

                let newRes = res.map((m) => {
                    return {
                        prop: 'extField.' + m.prop,
                        label: m.label,
                        align: 'center',
                        showOverflowTooltip: true
                    };
                });

                this.newColumns = [...this.columns, ...newRes, ...privateColumn];

                this.$forceUpdate();
            });
        },

        // 完结与批量完结
        toEnd(row) {
            if (row) {
                this.$confirm(`是否要完结工单【${row.code}】？`, '提醒', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        batchCompletion([row.id]).then((res) => {
                            this.$message.success('成功');
                            this.reload();
                        });
                    })
                    .catch(() => { });
            } else {
                if (!this.selection.length) {
                    return this.$message.warning('请至少选择一条工单！');
                }
                const ids = [];
                this.selection.map((item) => {
                    ids.push(item.id);
                });
                const h = this.$createElement;
                this.$msgbox({
                    title: '提醒',
                    message: h('p', null, [
                        h('span', null, '是否要完结 '),
                        h(
                            'span',
                            { style: 'color: #70B603' },
                            `${this.selection.length}`
                        ),
                        h('span', null, ' 条工单?')
                    ]),
                    showCancelButton: true,
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        batchCompletion(ids).then((res) => {
                            this.$message.success('成功');
                            this.reload();
                        });
                    })
                    .catch(() => { });
            }
        },

        // 取消完结
        toCancel(row) {
            cancelCompletion([row.id]).then((res) => {
                this.$message.success('成功');
                this.reload();
            });
        },

        // 拆分
        toUnpack(row) {
            this.$refs.unpackRef.open(row);
        },
        handleTabChange() {
            this.$refs.searchRef.reset();
        },

        /* 刷新表格 */
        reload(where = {}) {
            this.$nextTick(() => {
                where.statusList = (
                    where.status || this.statusOpt[this.activeName][0].value
                ).split(',');
                this.$refs.table.reload({ page: 1, where });
            });
        },

        // 生产工单跳转
        goDetail(row) {

            this.$refs.detailsRef.open(row)
        },
        handleDelete({ id }) {
            this.$confirm('确定删除当前数据?', '提示').then(async () => {
                await del(id);
                this.$message.success('删除成功！');
                this.reload();
            });
        },

        handleQRcode(row) {
            if (this.clientEnvironmentId == 2) {
                this.$refs.printSrRef.open([row.id]);
            } else if (this.clientEnvironmentId == 3) {
                this.$refs.printTgRef.open([row.id]);
            } else {
                this.$refs.printRef.open([row.id]);
            }
        },

        allPrinting() {
            let ids = this.findAllIds(this.selection);

            if (this.clientEnvironmentId == 2) {
                this.$refs.printSrRef.open(ids);
            } else if (this.clientEnvironmentId == 3) {
                this.$refs.printTgRef.open(ids);
            } else {
                this.$refs.printRef.open(ids);
            }
        },

        findAllIds(nodes) {
            let ids = [];
            nodes.forEach((node) => {
                ids.push(node.id); // 添加当前节点的id
                if (node.children && node.children.length > 0) {
                    // 递归调用自身来处理子节点
                    ids = ids.concat(this.findAllIds(node.children));
                }
            });
            return ids;
        },

        choose(row) {
            this.updateFn(row);
        },

        async updateFn(row) {
            let req = {
                id: this.id,	//工艺路线id		false	
                produceRoutingId: row[0].id,	//工艺路线id		false	
                produceRoutingName: row[0].name,

            };
            const res = await update(req);
            this.reload();
        },

        sortTop(row) {
            row.priority = Number(row.priority) + 1;
            this.priorityChange(row);
        },
        sortBottom(row) {
            if (row.priority <= 1) {
                return;
            }
            row.priority = Number(row.priority) - 1;
            this.priorityChange(row);
        },

        priorityChange(row) {
            if (row.priority > 10) {
                row.priority = 10; // 如果大于 10，则设置为 10
            } else if (row.priority < 0) {
                row.priority = 0; // 如果小于 0，则设置为 0
            }

            this.priorityFn(row);
        },
        priorityFn: debounce(function (row) {
            let params = {
                id: row.id,
                priority: row.priority
            };
            updatePriority(params).then((res) => { });
        }, 800)
    }
};
</script>