<template>
    <a-card title="订单处理" :bordered="false">
        <template #extra>
            <a-button style="margin-left: 10px;" type="primary" @click="Refresh()">刷新</a-button>
        </template>
        <a-collapse v-model:activeKey="activeKey" accordion v-if="dataShow">
            <a-collapse-panel v-for="(item, index) in tableData" :key="index.toString()">
                <template slot="header">
                    <div style="font-size: 18px; font-weight: bold;">
                        采购订单号:HL-{{ item.requirementNumber }} &nbsp;&nbsp;部门:{{ item.sysOrgCode }}
                        &nbsp;&nbsp;采购方向:{{ item.procurementDirection }}
                        <a-button style="float: right;margin-left: 10px;" @click="generateOrder(item)">生成订单</a-button>
                        <a-button style="float: right;" @click="receiveNO(item)">取消接单</a-button>
                    </div>
                </template>
                <div>
                    <a-descriptions title="订单详情" bordered>
                        <a-descriptions-item label="申请人">{{ item.createBy_dictText }}</a-descriptions-item>
                        <a-descriptions-item label="申请时间">{{ item.createTime }}</a-descriptions-item>
                        <a-descriptions-item label="申请部门">{{ item.sysOrgCode }}</a-descriptions-item>
                        <a-descriptions-item label="采购类型">{{ item.procurementCategory_dictText }}</a-descriptions-item>
                        <a-descriptions-item label="采购预算" :span="3">{{ item.procurementBudget }}</a-descriptions-item>
                        <a-descriptions-item label="审批人">{{ item.approvedBy_dictText }}</a-descriptions-item>
                        <a-descriptions-item label="附件" :span="3">
                            <template>
                                <span v-if="!item.annex" style="font-size: 12px;font-style: italic;">无文件</span>
                                <a-button v-else :ghost="true" type="primary" icon="download" size="small"
                                    @click="downloadFile(item.annex)">
                                    下载
                                </a-button>
                            </template>
                        </a-descriptions-item>
                        <a-descriptions-item label="采购详情(未整理)"
                            v-if="item.supplierSelection == null || item.supplierSelection == ''">
                            <div v-for="(item2, index2) in item.procurementContent" :key="index2.toString()">
                                <a-row>
                                    <a-col :span="2">{{ item2.name }}</a-col>
                                    <a-col :span="2">{{ item2.number }}{{ item2.unit }}</a-col>
                                </a-row>
                            </div>
                            <a-button style="float: right;" type="primary" @click="arrangeOpen(item)">物品和供应商整理</a-button>
                        </a-descriptions-item>
                        <a-descriptions-item label="采购详情" v-else>

                            <a-card style="margin-top: 20px;margin-right: 20px;"
                                v-for="(item2, index2) in item.supplierSelection" :key="index2.toString()">
                                <template #title>
                                    {{ item2.supplier }}
                                </template>
                                <div v-for="(item3, index3) in item2.goods" :key="index3.toString()">
                                    <a-row :gutter="16" style="margin-top: 5px;">
                                        <a-col :span="8">
                                            <a-input v-model="item3.name" placeholder="物品名称" disabled />
                                        </a-col>
                                        <a-col :span="6">
                                            <a-input v-model="item3.number" placeholder="数量" disabled />
                                        </a-col>
                                        <a-col :span="6">
                                            <a-input v-model="item3.unit" placeholder="单位" disabled />
                                        </a-col>
                                    </a-row>
                                </div>
                            </a-card>

                            <a-button style="margin-top: 10px;float: right;" type="primary"
                                @click="arrangeOpen(item)">物品和供应商整理</a-button>

                        </a-descriptions-item>
                    </a-descriptions>
                </div>
            </a-collapse-panel>
        </a-collapse>
        <a-empty v-else>
            <template #description>
                <span>
                    订单为空
                </span>
            </template>
        </a-empty>

        <a-modal title="采购整理" :visible="arrange" @ok="arrangeOk" @cancel="arrangeCancel">
            <div v-if="classifyData.length == 0">
                暂无数据
            </div>
            <div v-else>
                <div>
                    <a-card style="margin-top: 20px;margin-right: 20px;" v-for="(item, index) in classifyData"
                        :key="index.toString()">
                        <template #title>
                            {{ item.supplier }}
                            <a-button style="float: right;" type="primary" @click="delSupplier(item)">删除公司</a-button>
                        </template>
                        <div style="margin-bottom: 20px;">
                            <a-select v-model:value="selectedFoods" mode="multiple" style="width: 60%"
                                placeholder="Please select">
                                <a-select-option v-for="food in classFood" :key="food.name" :value="food.name">
                                    {{ food.name }}
                                </a-select-option>
                            </a-select>

                            <a-button style="float: right;" @click="importFoods(index)">导入</a-button>
                            <br>
                        </div>
                        <div v-for="(item2, index2) in item.goods" :key="index2.toString()">
                            <a-row :gutter="16" style="margin-top: 5px;">
                                <a-col :span="8">
                                    <a-input v-model="item2.name" placeholder="物品名称" />
                                </a-col>
                                <a-col :span="6">
                                    <a-input v-model="item2.number" placeholder="数量" />
                                </a-col>
                                <a-col :span="6">
                                    <a-input v-model="item2.unit" placeholder="单位" />
                                </a-col>
                                <a-col :span="2">
                                    <!-- 通过点击按钮触发新增行 -->
                                    <a-icon type="plus-circle" @click="addRow(item2, index)" />
                                </a-col>
                                <a-col :span="2">
                                    <!-- 通过点击按钮触发删除行 -->
                                    <a-icon type="minus-circle" @click="removeRow(index, index2)" />
                                </a-col>
                            </a-row>
                        </div>

                    </a-card>
                </div>
            </div>
            <div>
                <a-select mode="default" v-model="selectedSuppliers" style="width: 160px;">
                    <a-select-option v-for="supplier in classSupplier" :key="supplier.id" :value="supplier.id">
                        {{ supplier.name }}
                    </a-select-option>
                </a-select>
                <a-button type="primary" style="margin-top: 20px;margin-left: 20px;" @click="addSupplier()">添加供应商</a-button>
            </div>
        </a-modal>

    </a-card>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { USER_INFO } from "@/store/mutation-types"
import Vue from 'vue'

export default {
    name: 'PurchaseOrderConfirmationList',
    data() {
        return {
            url: {
                getPurchaseSupplier: "Try/purchaseSupplier/list",
                getdata: "/Try/purchaseOrderConfirmation/joinList",
                receiveNOurl: "/Try/purchaseOrderConfirmation/cancelReceiving",
                editUrl: '/Try/purchaseOrderConfirmation/edit'
            },
            activeKey: [],
            username: Vue.ls.get(USER_INFO).username,
            sysOrgCode: Vue.ls.get(USER_INFO).orgCode,
            supplierList: [],
            tableData: [],
            dataShow: false,
            arrange: false,

            classifyData: [],
            classSupplier: [],
            selectedSuppliers: '',
            classFood: [],
            selectedFoods: [],
            poenNmber: '',
        }
    },
    computed: {
        getPurchaseSupplier: function () {
            return `${window._CONFIG['domianURL']}/${this.url.getPurchaseSupplier}`;
        },
        getdata: function () {
            return `${window._CONFIG['domianURL']}/${this.url.getdata}`;
        },
        receiveNOurl: function () {
            return `${window._CONFIG['domianURL']}/${this.url.receiveNOurl}`;
        },
        editUrl: function () {
            return `${window._CONFIG['domianURL']}/${this.url.editUrl}`;
        },
    },
    created() {
        this.getSupplierData();
        this.getTableData();
    },
    methods: {
        getSupplierData() {
            getAction(this.getPurchaseSupplier).then(res => {
                //如果为200，则获取数据
                if (res.code == 200) {
                    this.supplierList = res.result.records;
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        getTableData() {
            this.dataShow = false;
            getAction(this.getdata).then(res => {
                //如果为200，则获取数据
                if (res.code == 200) {
                    this.tableData = res.result.records;
                    //判断数据是否为空
                    if (this.tableData.length == 0) {
                        this.dataShow = false;
                    } else {
                        this.activeKey = [''];
                        //将采购详情转化为对象
                        this.tableData.forEach(item => {
                            item.procurementContent = JSON.parse(item.procurementContent);
                        });
                        //将supplierSelection转化为对象
                        this.tableData.forEach(item => {
                            if (item.supplierSelection != null && item.supplierSelection != '') {
                                item.supplierSelection = JSON.parse(item.supplierSelection);
                            }
                        });
                        this.dataShow = true;
                    }
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        receiveNO(item) {
            //深拷贝一份item
            let newItem = Object.assign({}, item);
            newItem.procurementContent = JSON.stringify(newItem.procurementContent);
            newItem.supplierSelection = JSON.stringify(newItem.supplierSelection);
            postAction(this.receiveNOurl, newItem).then(res => {
                //如果为200，则获取数据
                if (res.code == 200) {
                    this.$message.success('取消成功');
                    this.getTableData();
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        Refresh() {
            this.getSupplierData();
            this.getTableData();
        },
        downloadFile(text) {
            if (!text) {
                this.$message.warning("未知的文件")
                return;
            }
            if (text.indexOf(",") > 0) {
                text = text.substring(0, text.indexOf(","))
            }
            let url = this.getFileAccessHttpUrl(text)
            window.open(url);
        },
        getFileAccessHttpUrl(avatar, subStr) {
            if (!subStr) subStr = 'http'
            try {
                if (avatar && avatar.startsWith(subStr)) {
                    return avatar;
                } else {
                    if (avatar && avatar.length > 0 && avatar.indexOf('[') == -1) {
                        return window._CONFIG['staticDomainURL'] + "/" + avatar;
                    }
                }
            } catch (err) {
                return;
            }
        },
        generateOrder(item) {
            this.$message.success('生成订单成功');
        },
        //整理弹窗的确认提交
        arrangeOk() {
            this.classifyData.forEach((item, index) => {
                //遍历item中的goods
                item.goods.forEach((item2, index2) => {
                    //如果有一项为空，则删除这一项             
                    let flag1 = item2.name == null || item2.name == '' || item2.name == undefined;
                    let flag2 = item2.number == null || item2.number == '' || item2.number == undefined;
                    let flag3 = item2.unit == null || item2.unit == '' || item2.unit == undefined;
                    if (flag1 && flag2 && flag3) {
                        item.goods.splice(index2, 1);
                    }
                });
            });

            let data = {
                associationNumber: this.poenNmber,
                supplierSelection: JSON.stringify(this.classifyData),
            }
            if (data.supplierSelection == '[]') {
                data.supplierSelection = '';
            }
            postAction(this.editUrl, data).then(res => {
                if (res.code == 200) {
                    this.$message.success('整理成功');
                    this.arrange = false;
                    this.getTableData();
                    //将相关数据清空
                    this.classifyData = [];
                    this.classSupplier = [];
                    this.classFood = [];
                    this.selectedSuppliers = '';
                    this.selectedFoods = [];
                    this.poenNmber = '';
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        //取消整理
        arrangeCancel() {
            this.arrange = false;
            //将相关数据清空
            this.classifyData = [];
            this.classSupplier = [];
            this.classFood = [];
            this.selectedSuppliers = '';
            this.selectedFoods = [];
            this.poenNmber = '';
        },
        //打开整理弹窗,整理弹窗的数据初始化
        arrangeOpen(item) {
            //获取供应商数据
            this.classifyData = [];
            this.classSupplier = [];
            this.supplierList.forEach(item => {
                this.classSupplier.push({
                    id: item.id,
                    name: item.name,
                });
            });
            this.classSupplier = Object.assign([], this.classSupplier);
            //获取物品数据
            this.classFood = Object.assign([], item.procurementContent);
            this.poenNmber = item.requirementNumber;
            //判断supplierSelection是否为空或者null
            if (item.supplierSelection == null || item.supplierSelection == '') {
                this.arrange = true;
            }
            else {
                //将其转化为对象
                let newData = JSON.parse(JSON.stringify(item.supplierSelection))
                //将被选择的供应商从classSupplier中删除
                newData.forEach(item => {
                    this.classSupplier.forEach((item2, index2) => {
                        if (item2.id == item.supplierID) {
                            this.classSupplier.splice(index2, 1);
                        }
                    });
                });
                //将其添加到classifyData中
                this.classifyData = JSON.parse(JSON.stringify(newData))
                this.arrange = true;
            }
        },
        //以下为整理的相关操作
        delSupplier(item) {
            //搜索ID将这一行从classifyData中删除
            this.classifyData.forEach((item2, index2) => {
                if (item2.supplierID == item.supplierID) {
                    this.classifyData.splice(index2, 1);
                }
            });
            //将其添加到classSupplier中
            this.classSupplier.push({
                id: item.supplierID,
                name: item.supplier,
            });
        },
        addSupplier() {
            //如果选中的供应商为空，则不添加
            if (this.selectedSuppliers == '') {
                this.$message.warning('请选择供应商');
                return;
            }
            let selectedID = this.selectedSuppliers;
            let selectedSupplier = {};
            this.classSupplier.forEach((item, index) => {
                if (item.id == selectedID) {
                    selectedSupplier = Object.assign({}, item);
                    this.classSupplier.splice(index, 1);
                }
            });
            this.classifyData.push({
                supplierID: selectedSupplier.id,
                supplier: selectedSupplier.name,
                goods: [{
                    name: '',
                    number: '',
                    unit: '',
                }
                ],
            });
            //将选中制空
            this.selectedSuppliers = '';
        },
        addRow(item, index) {
            this.classifyData[index].goods.push({
                name: '',
                number: '',
                unit: '',
            });
        },
        removeRow(index1, index2) {
            this.classifyData[index1].goods.splice(index2, 1);
        },
        importFoods(index) {
            let selectedFoods = this.selectedFoods;
            let selectedGoods = [];
            this.classFood.forEach(item => {
                selectedFoods.forEach(item2 => {
                    if (item.name == item2) {
                        selectedGoods.push(item);
                    }
                });
            });
            //push而不是赋值，因为要保留原来的数据
            selectedGoods.forEach(item => {
                this.classifyData[index].goods.push({
                    name: item.name,
                    number: item.number,
                    unit: item.unit,
                });
            });
            this.selectedFoods = [];
        },
    },
}

</script>
<style></style>


