<!-- eslint-disable no-empty -->
<template>
    <div class="app-container">
        <div class="head-container">
            <el-row :gutter="20">
                <el-col :span="3">
                    <el-input v-model="query.conName" size="small" clearable placeholder="请输入耗材信息名称"
                        style="width: 100%;" class="filter-item" @keyup.enter.native="getTableData" />
                </el-col>
                <el-col :span="3">
                    <el-input v-model="query.specSnap" size="small" clearable placeholder="请输入规格名称" style="width: 100%;"
                        class="filter-item" @keyup.enter.native="getTableData" />
                </el-col>
                <el-col :span="3">
                    <el-input v-model="query.name" size="small" clearable placeholder="请输入商品名称" style="width: 100%;"
                        class="filter-item" @keyup.enter.native="getTableData" />
                </el-col>
                <el-col :span="3">
                    <el-select v-model="query.status" placeholder="请选择商品规格" style="width: 100%;">
                        <el-option :label="item.label" :value="item.value" v-for="item in typeEnums"
                            :key="item.label" />
                    </el-select>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="getTableData">查询</el-button>
                    <el-button @click="resetHandle">重置</el-button>
                </el-col>
            </el-row>
        </div>
        <div class="head-container">
            <el-row>
                <el-col>
                    <el-button type="primary" icon="el-icon-plus"
                        @click="$refs.shopList.show(tableData.list)">选择商品规格</el-button>
                </el-col>
            </el-row>
        </div>
        <div class="head-container" id="table_drag">
            <el-table ref="table" :data="tableData.data" v-loading="tableData.loading" row-key="id">
                <el-table-column prop="id" label="ID" width="50px" />
                <el-table-column label="耗材信息" prop="conName" />
                <el-table-column label="商品" prop="name" />
                <el-table-column label="规格" prop="specSnap" />
                <el-table-column label="单笔消耗数" prop="surplusStock" />
                <!-- <el-table-column label="价格" prop="conName" /> -->
                <el-table-column label="耗材信息代码" prop="conCode" />
                <el-table-column label="耗材信息单位" prop="conUnit" />
                <el-table-column label="库存" prop="stockNumber" />
                <el-table-column label="创建时间" prop="createTime">
                    <!-- <template v-slot="scope">
                        {{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
                    </template> -->
                </el-table-column>
                <el-table-column label="状态" prop="status">
                    <template v-slot="scope">
                        <el-tag type="primary" v-if="scope.row.status == '1'">启用</el-tag>
                        <el-tag type="danger" v-if="scope.row.status == '0'">禁用</el-tag>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="更新时间" prop="updateTime">
                    <template v-slot="scope">
                        {{ dayjs(scope.row.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" width="200">
                    <template v-slot="scope">
                        <!-- <el-button type="text" icon="el-icon-rank">排序</el-button> -->
                        <el-button type="text" icon="el-icon-edit"
                            @click="clickdialogframe('edit', scope.row)">编辑</el-button>
                        <el-popconfirm title="确定删除吗？" @confirm="delTableHandle([scope.row.id])">
                            <el-button type="text" icon="el-icon-delete" style="margin-left: 20px !important;"
                                slot="reference">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="head-container">
            <el-pagination :total="tableData.total" :current-page="tableData.page + 1" :page-size="tableData.size"
                layout="total, sizes, prev, pager, next, jumper" @current-change="paginationChange"
                @size-change="e => { tableData.size = e; getTableData() }" />
        </div>
        <el-dialog :title="dialogtitle" :visible.sync="dialogshow" width="1000px">
            <el-form ref="addSelect" :inline="true">
                <el-form-item label="商品名称">
                    <template v-for="(ele, index) in addSelect">
                        {{ addSelect.length ? addSelect[index].name : '' }}
                    </template>
                </el-form-item><br />

                <template v-for="(ele, index) in commodityArr">
                    <el-form-item label="商品规格">
                        <el-input v-model="ele.specSnap" style="width: 130px;" placeholder="请选择商品规格"
                            disabled></el-input>
                    </el-form-item>
                    <el-form-item label="耗材信息" prop="conName">
                        <el-input v-model="ele.conName" style="width: 130px;" placeholder="请选择耗材信息" disabled></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="selecthaocai(ele)">去选择耗材信息</el-button>
                    </el-form-item>
                    <el-form-item label="单位耗材值">
                        <el-input v-model="ele.surplusStock" type=number placeholder="请输入单位耗材值"></el-input>
                    </el-form-item>
                </template>

                <el-form-item style="display: flex;justify-content: flex-end;">
                    <el-button @click="dialogshow = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm('addSelect')">确 定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog title="耗材信息" :visible.sync="informationdialogshow">
            <div class="head-container">
                <el-input v-model="queryinformation.conTypeId" size="small" clearable placeholder="请输入类型id"
                    style="width: 100%;" class="filter-item" @keyup.enter.native="getTableDatainformation" />
                <el-input v-model="queryinformation.conTypeName" size="small" clearable placeholder="请输入类型名称"
                    style="width: 100%;" class="filter-item" @keyup.enter.native="getTableDatainformation" />
                <el-input v-model="queryinformation.conCode" size="small" clearable placeholder="请输入耗材代码"
                    style="width: 100%;" class="filter-item" @keyup.enter.native="getTableDatainformation" />
                <el-input v-model="queryinformation.conName" size="small" clearable placeholder="请输入耗材名称"
                    style="width: 100%;" class="filter-item" @keyup.enter.native="getTableDatainformation" />
                <div style="display: flex; justify-content: flex-end;">
                    <el-button style="margin-right: 20px;" type="primary"
                        @click="getTableDatainformation">查询</el-button>
                    <el-button @click="resetHandleinformation">重置</el-button>
                </div>
            </div>
            <el-table ref="table" :data="tableDatainformation.data" v-loading="tableDatainformation.loading"
                row-key="id">
                <el-table-column prop="id" label="ID" width="50px" />
                <el-table-column label="耗材名称" prop="conName" />
                <el-table-column label="耗材代码" prop="conCode" />
                <el-table-column label="类型名称" prop="conTypeName" />
                <el-table-column label="单位" prop="conUnit" />
                <el-table-column label="库存数量" prop="stockNumber">
                    <template v-slot="scope">
                        {{ (scope.row.stockNumber - scope.row.stockConsume).toFixed(2) }}
                    </template>
                </el-table-column>

                <el-table-column label="单位耗材值" prop="surplusStock" />
                <el-table-column label="" width="200">
                    <template v-slot="scope">
                        <el-button @click="tableDatainformationtable(scope.row)">确定</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="head-container">
                <el-pagination :total="tableDatainformation.total" :current-page="tableDatainformation.page + 1"
                    :page-size="tableDatainformation.size" layout="total, sizes, prev, pager, next, jumper"
                    @current-change="paginationChangeinformation"
                    @size-change="e => { tableDatainformation.size = e; tableDatainformation.page = 0; getTableDatainformation() }" />
            </div>
        </el-dialog>
        <el-dialog title="编辑" :visible.sync="informationdialogshowedit" width="20%">
            <el-form ref="addSelect" :inline="true">
                <el-form-item label="单位耗材值">
                    <el-input v-model="surplusStocks.surplusStock" type=number
                        @input="limitInput($event, 'monthOutputValue')" placeholder="请输入单位耗材值"></el-input>
                </el-form-item>
                <el-form-item style="display: flex;justify-content: flex-end;">
                    <el-button @click="informationdialogshowedit = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm('addSelect')">确 定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <shopList ref="shopList" @success="selectShop" />

    </div>
</template>

<script>
import Sortable from 'sortablejs'
import dayjs from 'dayjs'
import shopList from '../components/shopList'
import { upProSort, tbProduct } from '@/api/shop'
import { getviewConSku, gettbProductSpec, gettbConsInfo, posttbProskuCons, puttbProskuCon, deletetbProskuCon } from '@/api/consumable'
export default {
    components: { shopList },
    data() {
        return {
            dayjs,
            query: {
                conName: '',
                specSnap: '',
                name: '',
                status: ''
            },
            surplusStocks: '',
            typeEnums: [{
                label: '正常',
                value: '1'
            }, {
                label: '禁用',
                value: '0'
            }],
            dialogshow: false, //弹框显示
            dialogtitle: '', //文字显示
            informationdialogshow: false,
            informationdialogshowedit: false,
            tableData: {
                data: [],
                page: 0,
                size: 30,
                loading: false,
                total: 0
            },
            queryinformation: {
                conTypeId: '',
                conTypeName: '',
                conCode: '',
                conName: ''
            },
            tableDatainformation: {
                data: [],
                page: 0,
                size: 30,
                loading: false,
                total: 0
            },
            tableDataskudialogshow: false,
            querytableDatasku: {
                specSnap: '',
                name: '',
                shopName: ''
            },
            tableDatasku: {
                data: [],
                page: 0,
                size: 30,
                loading: false,
                total: 0
            },
            rules: {

            },
            // 动态新增选择框-所有数据
            addSelect: [],
            // 筛选集合
            commodityArr: [],
            // 选择耗材的index
            ALLisDistribute: null,
        }
    },
    mounted() {
        this.getTableData()
        this.getTableDatasku()
        this.getTableDatainformation()
        this.$nextTick(() => {
            // this.tableDrag()
            // this.$refs.shopList.isselectEvent()
        })
    },
    methods: {
        limitInput(value, name) {
            this.surplusStocks.surplusStock = ('' + value) // 第一步：转成字符串
                // .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉

                .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字

                .replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全

                .match(/^\d*(\.?\d{0,2})/g)[0] || ''
        },
        selectShop(res) {
            this.commodityArr = []
            this.addSelect = res
            console.log(res, 'tiaosjo')
            res.forEach((ele, i) => {
                // isDistribute1为共享库存-商品，0不共享是多规格
                // 判断是否共享拆分数据到商品和规格集合里
                let sname = ele.name
                if (ele.isDistribute == 1) {
                    ele.specSnap = ele.name
                    ele.conName = ele.conName
                    this.commodityArr.push(ele)
                } else {
                    // 规格数据处理
                    ele.skuList.forEach(element => {
                        element.conInfoId = element.id
                        element.conName = element.conName
                        this.commodityArr.push(element)
                        if(element.specSnap==null){
                            element.specSnap=sname
                        }
                    })
                }
            })
            this.clickdialogframe('add')

        },
        // 选择耗材
        selecthaocai(item) {
            this.ALLisDistribute = item
            this.informationdialogshow = true
        },
        //表格拖拽
        tableDrag() {
            const el = document.querySelector('#table_drag .el-table__body-wrapper tbody')
            new Sortable(el, {
                animation: 150,
                onEnd: async e => {
                    // console.log('拖拽结束===', e);
                    if (e.oldIndex == e.newIndex) return
                    let oid = this.tableData.data[e.oldIndex].id
                    let nid = this.tableData.data[e.newIndex].id
                    let ids = this.tableData.data.map(item => item.id)
                    try {
                        await upProSort({
                            strId: oid,
                            endId: nid,
                            ids: ids
                        })
                        await this.getTableData()
                    } catch (error) {
                        console.log(error)
                    }
                }
            })
        },
        // 重置查询
        resetHandle() {
            this.query.conName = ''
            this.query.specSnap = ''
            this.query.name = ''
            this.query.status = ''
            this.tableData.page = 0
            this.getTableData()
        },
        resetHandlesku() {
            this.querytableDatasku.specSnap = ''
            this.querytableDatasku.name = ''
            this.querytableDatasku.shopName = ''
            this.tableDatasku.page = 0
            this.getTableDatasku()
        },
        resetHandleinformation() {
            this.queryinformation.conTypeId = ''
            this.queryinformation.conTypeName = ''
            this.queryinformation.conCode = ''
            this.queryinformation.conName = ''
            this.tableDatainformation.page = 0
            this.getTableDatainformation()
        },
        // 分页回调
        paginationChange(e) {
            this.tableData.page = e - 1
            this.getTableData()
        },
        // 获取商品列表
        async getTableData() {
            this.tableData.loading = true
            try {
                const res = await getviewConSku({
                    page: this.tableData.page,
                    size: this.tableData.size,
                    conName: this.query.conName,
                    specSnap: this.query.specSnap,
                    name: this.query.name,
                    status: this.query.status,
                    shopId: localStorage.getItem('shopId')
                })
                this.tableData.loading = false
                this.tableData.data = res.content
                this.tableData.total = res.totalElements
            } catch (error) {
                console.log(error)
            }
        },
        paginationChangeinformation(e) {
            this.tableDatainformation.page = e - 1
            this.getTableDatainformation()
        },
        // 获取信息管理
        async getTableDatainformation() {
            this.tableDatainformation.loading = true
            try {
                const res = await gettbConsInfo({
                    page: this.tableDatainformation.page,
                    size: this.tableDatainformation.size,
                    shopId: localStorage.getItem('shopId'),
                    conTypeId: this.queryinformation.conTypeId,
                    conTypeName: this.queryinformation.conTypeName,
                    conCode: this.queryinformation.conCode,
                    conName: this.queryinformation.conName,
                })
                this.tableDatainformation.loading = false
                this.tableDatainformation.data = res.content
                this.tableDatainformation.total = res.totalElements
            } catch (error) {
                console.log(error)
            }
        },
        // 耗材信息的信息
        tableDatainformationtable(item) {
            this.commodityArr.forEach(ele => {
                if (ele.id == this.ALLisDistribute.id) {
                    ele.consInfoId = item.id
                    ele.conName = item.conName
                    ele.skuId = ele.id
                }
            })
            this.informationdialogshow = false
        },
        // 获取商品规格
        async getTableDatasku() {
            this.tableDatasku.loading = true
            try {
                const res = await tbProduct({
                    page: this.tableDatasku.page,
                    size: this.tableDatasku.size,
                    shopId: localStorage.getItem('shopId'),
                    specSnap: this.querytableDatasku.specSnap,
                    name: this.querytableDatasku.name,
                    sort: 'id.desc',
                    shopName: this.querytableDatasku.shopName
                })
                this.tableDatasku.loading = false
                this.tableDatasku.data = res.content
                this.tableDatasku.total = res.totalElements
            } catch (error) {
                console.log(error)
            }
        },
        Changeinformationsku(e) {
            this.tableDatasku.page = e - 1
            this.getTableDatasku()
        },
        // 弹框修改值  添加  编辑
        clickdialogframe(type, item) {
            if (type == 'add') { // 添加
                this.dialogtitle = '添加'
                this.$nextTick(() => {
                    this.$refs.addSelect.resetFields()
                })
                this.dialogshow = true
            } else {
                this.informationdialogshowedit = true
                this.dialogtitle = '编辑'
                this.surplusStocks = item
            }
        },
        async submitForm(formName) {
            if (this.dialogtitle == '编辑') {
                let { id, surplusStock } = this.surplusStocks
                await puttbProskuCon({
                    id,
                    surplusStock
                })
                this.$message({
                    message: '修改成功',
                    type: 'success'
                });
                this.informationdialogshowedit = false
            } else {
                // isDistribute1为共享库存-商品，0不共享是多规格
                let isgongx = false
                this.commodityArr.forEach(ele => {
                    if (!ele.skuId || !ele.surplusStock) {
                        isgongx = true
                    }
                })
                if (isgongx) {
                    this.$message.error('请选择耗材信息与输入耗材值')
                    isgongx = false
                    return
                }
                this.addSelect.forEach(ele => {
                    ele.skuInfos = ele.skuList
                    ele.productId = ele.id //商品id
                })
                await posttbProskuCons(this.addSelect)
                this.$message({
                    message: '新增成功',
                    type: 'success'
                });
                this.ALLisDistribute = null
                this.dialogshow = false
            }
            this.$refs[formName].resetFields()
            this.getTableData()

        },
        resetForm(formName) {
            this.$refs[formName].resetFields()
        },
        // 删除商品
        async delTableHandle(ids) {
            try {
                await deletetbProskuCon(ids)
                this.getTableData()
            } catch (error) {
                console.log(error)
            }
        }
    }
}
</script>

<style scoped lang="scss">
.handle {
    font-size: 18px;
    color: #999;

    &:hover {
        cursor: grab;
    }
}

.shop_info {
    display: flex;

    .info {
        flex: 1;
        padding-left: 8px;
        display: flex;
        flex-direction: column;

        .tag_wrap {
            display: flex;
        }
    }
}
</style>