<template>
    <div class="bg-in-stock">
        <el-form ref="productListAddForm" :model="productListAddForm" :rules="productListAddFormRule"
            :disabled="isDetail" label-width="160px" inline class="change-form">
            <div class="mx">
                <el-form-item label="分类类型" prop="hire_or_sail" class="change-form-item">
                    <el-select v-model="productListAddForm.hire_or_sail" clearable @change="selhire_or_sail">
                        <el-option label="售卖商品" value="sail" />
                        <el-option label="出租商品" value="hire" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分类名称" prop="name" class="change-form-item">
                    <el-input v-model="productListAddForm.name" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark" class="change-form-item" style="width: 61%">
                    <el-input style="flex: 1" v-model="productListAddForm.remark" type="textarea"
                        :disabled="type === 'detail' || type === 'audit'" :autosize="{ minRows: 3, maxRows: 4 }"
                        placeholder="请输入"></el-input>
                </el-form-item>
            </div>
            <div class="mx">
                <h3>分类商品</h3>
                <el-button class="button" size="mini" type="primary" :disabled="type === 'check'"
                    v-if="type !== 'detail' && type !== 'audit'" @click="handleSelectWarehouseEntryBatch">选择</el-button>
            </div>
            <div style="width: 100%; display: block">
                <el-form-item style="width: 100%">
                    <el-table :data="productListAddForm.item_do_list" border :cell-style="{ textAlign: 'center' }"
                        :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px">
                        <el-table-column label="商品编号">
                            <template slot-scope="scope">
                                {{ scope.row.goods_vo.sn }}
                            </template>
                        </el-table-column>
                        <el-table-column label="商品名称">
                            <template slot-scope="scope">
                                {{ scope.row.goods_vo.name }}
                            </template>
                        </el-table-column>
                        <el-table-column label="条码">
                            <template slot-scope="scope">
                                {{ scope.row.bar_code }}
                            </template>
                        </el-table-column>
                        <!--      <el-table-column label="序列号">
                            <template slot-scope="scope">
                                {{ scope.row.sn_code }}
                            </template>
                        </el-table-column> -->
                        <el-table-column prop="spec_name" label="规格型号">
                        </el-table-column>
                        <el-table-column label="单位">
                            <template slot-scope="scope">
                                {{ scope.row.unit }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" v-if="type !== 'detail' && type !== 'audit'">
                            <template slot-scope="scope">
                                <el-button size="mini" type="danger" @click="
                                    productListAddForm.item_do_list.splice(scope.$index, 1)
                                    ">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </div>
        </el-form>
        <div class="footer">
            <el-button v-if="type !== 'audit' && type !== 'detail'" type="primary" :disabled="type === 'check'"
                @click="saveproductListAddForm">添加
            </el-button>
            <el-button @click="$router.back()">返回</el-button>
        </div>

        <el-dialog title="商品列表" :visible.sync="goodsVisible" width="1000px" @close="closeGoosData">
            <el-table ref="table" :data="goodsData" border style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="goods_vo.sn" label="商品编号"> </el-table-column>
                <el-table-column prop="bar_code" label="商品条码"> </el-table-column>
                <el-table-column prop="sn_code" label="序列号"> </el-table-column>
                <el-table-column prop="goods_vo.name" label="商品名称"> </el-table-column>
                <el-table-column prop="spec_name" label="规格型号">
                </el-table-column>
                <el-table-column prop="unit" label="单位"> </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeGoosData">取 消</el-button>
                <el-button type="primary" @click="submitGoosData()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import { Foundation, RegExp } from "~/ui-utils";
import * as API_GoodsExchange from "@/api/goodsExchange";
import * as API_GoodsLend from "@/api/goodsLend"
import * as API_Setting from "@/api/setting";
import * as API_BasicSetting from "@/api/basicSetting";
import * as API_Erp from "@/api/erp";
import * as API_Auth from "@/api/auth";
import * as API_productClass from "@/api/productClass.js"
export default {
    name: "goodsExchangeAdd",
    data() {
        return {
            typeList: [],
            adminList: [],
            dialogVisible: false,
            warehouseList: [],
            deptList: [],
            deptListAll: [],
            orderList: [],
            params:{
                pages: 1,
                size: 10
            },
            id: "",
            type: "",
            /** 出库单表单*/
            productListAddForm: {
                item_do_list: [],
                type: "",
                hire_or_sail:''
            },
            /** 校验规则 */
            productListAddFormRule: {
                name: [this.MixinRequired("请填写组合名称", "blur")],
                hire_or_sail: [this.MixinRequired("请选择商品类型", "change")],
            },
            warehouseProduct: null,
            scanDialogVisible: false,
            scanGoodsForm: {},
            //出入库
            sttorageType: "",
            // 出库商品明细
            goodsVisible: false,
            goodsData: [],
            // 暂存已勾选商品
            goodsList: [],
            item_do_list: [],
            code: "", //当前库位号
            warehouse_id: "",//当前仓库id
            activeList: [],//选中的商品
            isDetail: undefined,
        };
    },
    mounted() {
        this.id = this.$route.params.id
        this.type = this.$route.params.type
        if (this.type === 'check') {
            this.isDetail = true
            this.GET_goodsExchangeAddDetail();
        }
        this.GET_WarehouseList();
        this.GET_DeptList();
        this.outType();
    },
    watch: {
        $route: {
            immediate: true,
            handler(newVal) {
                if (newVal.name === "productClassEdit") {
                    this.GET_goodsExchangeAddDetail();
                }
            },
        },
    },
    computed: {
        ...mapGetters(["user"]),
    },
    methods: {
        selhire_or_sail(){
            this.productListAddForm.item_do_list=[]
        },
        // 保存已选商品
        submitGoosData() {
            if (this.goodsList.length >= 1) {
                this.productListAddForm.item_do_list = this.goodsList
                this.goodsVisible = false;
            } else {
                this.$message.error("请选择商品信息");
            }
        },
        //选择商品
        handleSelectionChange(val) {
            this.goodsList = val
        },
        // 关闭商品明细
        closeGoosData() {
            this.goodsVisible = false;
        },
        //获取出库类型字典
        outType() {
            API_Setting.getPage({ dictType: "out_warehouse_type" }).then((res) => {
                this.typeList = res.data.filter((el) => {
                    if (el.value !== "SALE_OUT" && el.value !== "HAIL_OUT") {
                        return el;
                    }
                });
            });
        },
        // 打印功能
        printIng() { },
        toSearch() {
            API_GoodsExchange.getGoodsInfo({
                barcode: this.scanGoodsForm.bar_code,
            }).then((res) => { });
        },
        // 扫码入库
        scanCode() {
            this.scanDialogVisible = true;
            this.$nextTick(() => {
                this.$refs.input.focus();
            });
        },
        /** 获取人员列表 */
        GET_AdministratorList() {
            API_Auth.getAdministratorList({
                page_no: 1,
                page_size: 9999,
                user_state: 0,
            }).then((response) => {
                this.adminList = response.data;
            });
        },
        /** 获取仓库 */
        GET_WarehouseList(e) {
            API_BasicSetting.getWarehouseListAll().then((response) => {
                this.warehouseList = response;
            });
        },
        //保存
        saveproductListAddForm() {
            this.$refs["productListAddForm"].validate((valid) => {
                if (valid) {
                    const { id } = this.productListAddForm;
                    const params = this.MixinClone(this.productListAddForm);
                    const query = []
                    if (!this.productListAddForm.item_do_list.length) {
                        this.$message.error("请选择商品！");
                        return;
                    }
                    params.item_do_list.map(el => {
                            el.product_id = el.id
                            el.id = ''
                        })
                    if (id) {
                       /*  params.item_do_list.map(el => {
                            el.id = ''
                        }) */
                        API_productClass.editProduct(id, params).then(() => {
                            this.$message.success("修改成功！");
                            const { callback } = this.$route.params;
                            if (typeof callback === "function") callback();
                            this.$store.dispatch("delCurrentViews", {
                                view: this.$route,
                                $router: this.$router,
                            });
                            this.$router.push({ name: "productClass" });
                        });
                    } else {
                        API_productClass.productGroup(params).then(() => {
                            this.$message.success("添加成功！");
                            const { callback } = this.$route.params;
                            if (typeof callback === "function") callback();
                            this.$store.dispatch("delCurrentViews", {
                                view: this.$route,
                                $router: this.$router,
                            });
                            this.$router.push({ name: "productClass" });
                        });
                    }

                }
            });
        },
        reverseSelect(rows) {
            this.$refs.table.toggleRowSelection(rows);
        },
        // 商品列表
        async handleSelectWarehouseEntryBatch() {
            if (this.productListAddForm.hire_or_sail !== '') {
                this.params.hire_or_sail=this.productListAddForm.hire_or_sail
                API_productClass.getProduct(this.params).then((res) => {
                    this.goodsData = res.data;
                    this.goodsVisible = true;
                    console.log(res);
                    /* API_GoodsLend.getInfo({ id: this.id }).then(response => {
                        this.activeList = response.area_stock_vo
                        res.records.map(item => {
                            response.area_stock_vo.map(el => {
                                if (item.id === el.product_stock_id) {
                                    this.reverseSelect(item)
                                }
                            })
                        })
                    }) */
                });
            }else{
                this.$message.error("请先选择商品分类类型")
            }

        },
        /** 选择订单编号 */
        async handleSelectOrderSn() {
            const orders = await this.$EnPickerOrder({
                orderApi: "admin/erp/order",
                selectedIds: [this.productListAddForm.order_sn],
                limit: 1,
            });
            this.$set(
                this.productListAddForm,
                "distribution_name",
                orders[0].distribution_name
            );
            const orderIds = orders.map((v) => v.sn);
            this.$set(this.productListAddForm, "order_sn", orderIds.join(","));
            this.GET_WarehouseOutProduct();
        },
        /** 获取出库单商品明细 */
        async GET_WarehouseOutProduct() {
            const res = await API_Erp.getWarehouseOutProduct({
                order_sn: this.productListAddForm.order_sn,
            });
            this.productListAddForm.return_list = res.data.map((item) => {
                item.amount = item.product_price;
                item.product_sn = item.product_sn;
                item.product_name = item.product_name;
                item.specification = item.product_specification;
                item.product_id = item.product_id;
                item.unit = item.product_unit;
                item.out_num = item.return_num;
                item.stock_sn = item.warehouse_entry_sn;
                item.cost_price = item.product_cost_price;
                return item;
            });
        },
        /** 获取仓库 */
        GET_DeptList() {
            API_GoodsExchange.getInfo().then((response) => {
                this.deptListAll = response;
                this.deptListAll.password = "";
            });
        },
        /** 切换仓库 */
        handleChangeWareHouse(val) {
            //this.productListAddForm.item_do_list = []change_list
        },
        /** 获取详情页面数据 */
        GET_goodsExchangeAddDetail() {
            this.$nextTick(() => {
                API_productClass.getById(this.id).then(res => {
                    res.item_do_list.map(el => {
                        el.bar_code = el.product_vo.bar_code
                        el.spec_name = el.product_vo.spec_name
                        el.unit = el.product_vo.unit
                    })
                    this.productListAddForm = res
                })
            });
        },
    },
};
</script>

<style type="text/scss" lang="scss" scoped>
/** 底部步骤 */
.footer {
    width: 100%;
    padding: 10px;
    bottom: 0px;
    text-align: center;
    z-index: 999;
}

.mx {
    display: flex;
    align-items: center;
    width: 100%;

    .button {
        margin-left: 10px;
    }
}

.change-form {
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    flex-wrap: wrap;
    min-width: 900px;

    .change-form-item {
        width: 30%;
        margin: 0 10px 20px 0;
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
    }

    /deep/ {
        .el-form-item__content {
            flex: 1;
            width: 100%;
        }

        .el-date-editor,
        .el-cascader,
        .el-select {
            width: 100%;
        }
    }
}

.bg-in-stock {
    background-color: #fff;
    margin: 10px;
    padding: 25px;
}

.goods-info {
    display: flex;

    .goods-name-box {
        text-align: left;

        .goods-name {
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            line-height: 16px;
        }

        .specs {
            color: #999999;
        }
    }
}

/deep/ {
    .el-input--suffix .el-input__inner {
        padding-right: 10px;
    }

    .error-input {
        .el-input__inner {
            border: 1px solid red;
        }
    }
}
</style>