<template>
    <div class="common-card">
        <h3>药品明细</h3>
        <div class="right-type">
            <el-button
                class="lake-Blue"
                type="primary"
                icon="el-icon-plus"
                @click="handleAdd"
            >添加药品
            </el-button>
        </div>
        <el-form :model="list" ref="listRef">
        <el-table
            style="margin-top: 30px;"
            v-loading="listLoading"
            element-loading-text="加载中"
            :data="list"
            fit
            stripe
            border
        >
            <template slot="empty">
                <img src="@/assets/nopage.png" alt />
                <p>暂无数据</p>
            </template>
            <el-table-column fixed type="index" label="序号" width="60"/>
            <el-table-column label="药品编码" prop="drugListId" />
            <el-table-column label="药品信息" prop="drugName,dosformName,essdrugType,prodentpName,specName,convrat,prepunt,pacUnt" width="300" >
                <template slot-scope="scope">
                    <div class="drug-name">
                        <el-tag>{{ scope.row.drugName }}</el-tag>{{ "【" + scope.row.dosformName + "】" }} 
                        <el-tag>{{ scope.row.essdrugType }}</el-tag><br />
                        {{ "生产厂家 【" + scope.row.prodentpName + "】" }}<br />
                        {{ '药品规格 【'+scope.row.specName +'*' +scope.row.convrat +scope.row.prepunt +'/' +scope.row.pacUnt +'】' }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="申请数量" prop="appyCnt" >
                <template slot-scope="scope">
                    <el-form-item
                        label-width="0"
                        class="item"
                        :prop="scope.$index + '.appyCnt'"
                        :rules="[
                        {
                            required: true,
                            pattern: /^[1-9]\d*$/,
                            message: '请输入正整数',
                            trigger: 'blur',
                        },
                        ]"
                    >
                        <el-input placeholder="请输入" v-model="scope.row.appyCnt" @change="handleInput"></el-input>
                    </el-form-item>
                </template>
            </el-table-column>
            <el-table-column label="当前库存" prop="invCnt" />
            <el-table-column label="最低库存" prop="lowInv" />
            <el-table-column label="最高库存" prop="highInv" />
            <el-table-column label="操作" width="100">
                <template slot-scope="scope">
                    <el-button
                        class="red"
                        type="text"
                        @click="handleDelete(scope.$index)"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        </el-form>
        <p class="price-css">合计数量：{{ amount.num }}</p>

        <div class="foot-button">
            <el-button type="primary" @click="handleSave" :loading="ssLoad">保存</el-button>
            <el-button type="success" @click="handleSubmit" :loading="bbLoad">提交</el-button>
        </div>

        <!-- 添加药品 -->
        <el-dialog
            title="选择药品"
            :visible.sync="dialogTable"
            width="60%">
                <el-form :model="tableForm" ref="tableform" :inline="true">
                    <el-form-item label="药品信息" prop="drugInfo" class="long">
                        <el-input v-model="tableForm.drugInfo" placeholder="请输入药品名称/编码/生产企业"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="getTableData('search')">查询 </el-button>
                        <el-button @click="tableReset">重置</el-button>
                    </el-form-item>
                </el-form>
            <el-table
                v-loading="tableLoading"
                element-loading-text="加载中"
                :data="tableData"
                ref="ta"
                fit
                stripe
                border
                @selection-change="handleSelectionChange"
                row-key="drugListId"
            >
                <template slot="empty">
                    <img src="@/assets/nopage.png" alt />
                    <p>暂无数据</p>
                </template>
                <el-table-column type="selection" width="60" :reserve-selection="true" :selectable="selectable"/>
                <el-table-column fixed type="index" label="序号" width="60"/>
                <el-table-column label="药品编码" prop="drugListId" />
                <el-table-column align="left" label="药品名称" prop="a,b,c,d,e" width="300">
                    <template slot-scope="scope">
                        <div class="drug-name">
                            <el-tag>{{ scope.row.drugName }}</el-tag>{{ "【" + scope.row.dosformName + "】" }} 
                            <el-tag>{{ scope.row.essdrugType }}</el-tag><br />
                            {{ "生产厂家 【" + scope.row.prodentpName + "】" }}<br />
                            {{ '药品规格 【'+scope.row.specName +'*' +scope.row.convrat +scope.row.prepunt +'/' +scope.row.pacUnt +'】' }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="剂型" prop="dosformName" />
                <el-table-column label="规格信息" prop="specName" />
                <el-table-column label="包装单位" prop="pacUnt" />
                <el-table-column label="当前库存" prop="invCnt" />
                <el-table-column label="生产企业" prop="prodentpName" />
            </el-table>
            <!--分页-->
            <yl-pagination
                v-show="tableTotal > 0"
                :total="tableTotal"
                :page.sync="tableForm.current"
                :limit.sync="tableForm.size"
                @pagination="getTableData"
            />
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogTable = false">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确认</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import ylPagination from "@/components/yl-pagination";
import { getDetlList,saveAppy,submitAppy,getOrgHospList } from "@/api/applyManage/index";
import { countNumPrice } from "@/utils/utils";
    export default {
        components: {
            ylPagination
        },
        data() {
            return {
                listLoading: false,
                list: [],
                dialogTable: false,
                tableLoading: false,
                tableData: [],
                tableForm:{
                    current: 1,
                    size: 10,
                    drugInfo: "",
                },
                tableTotal: 0,
                selectData: [],
                ssLoad: false,
                bbLoad: false,
                amount: {
                    num: 0,
                },
                essdrugOptions: ["非基药","基药"],
            }
        },
        mounted () {
            if(this.$route.query.type != 'add'){
                this.getData();
            }
        },
        methods: {
            getData() {
                this.listLoading = true;
                getDetlList({id: this.$route.query.id}).then((res) => {
                    this.list = res.data;
                    this.list.forEach((i)=>{
                        i.essdrugType = this.essdrugOptions[i.essdrugType*1]
                    })
                    this.listLoading = false;
                    this.amount = countNumPrice(this.list,'appyCnt');
                })
                .catch((err) => {
                    this.listLoading = false;
                });
            },
            // 采购数量书写完毕后计算合计数量
            handleInput(){
                this.amount = countNumPrice(this.list,'appyCnt');
            },
            // 添加药品
            handleAdd(){
                this.dialogTable = true;
                this.getTableData();
            },
            // 获取药品信息
            getTableData(type){
                if (type == "search") {
                    this.tableForm.current = 1;
                }
                this.tableLoading = true;
                getOrgHospList(this.tableForm).then((res) => {
                    this.tableData = res.data.records;
                    this.tableData.forEach((i)=>{
                        i.essdrugType = this.essdrugOptions[i.essdrugType*1]
                    })
                    this.tableTotal = res.data.total;
                    this.$refs.ta.clearSelection();
                    // 勾选已添加药品
                    // this.$nextTick(()=>{
                    //     this.tableData.forEach((row) => {
                    //         this.list.forEach((i)=>{
                    //             if (row.drugListId == i.drugListId) {
                    //                 this.$refs.ta.toggleRowSelection(row);
                    //             }
                    //         })
                    //     })
                    // })
                    this.tableLoading = false;
                })
                .catch((err) => {
                    this.tableLoading = false;
                });
            },
            selectable(row){
                if (this.list.some((el) => {return el.drugListId === row.drugListId;})) {
                    return false;
                } else {
                    return true;
                }
            },
            // 添加药品 重置
            tableReset(){
                this.$refs.tableform.resetFields();
                this.getTableData();
            },
            // 添加药品 多选
            handleSelectionChange(e){
                this.selectData = e;
            },
            // 添加药品 确认
            handleConfirm(){
                if(this.selectData.length != 0){
                    this.selectData.forEach((i)=>{
                        this.list.push(i);
                    })
                    this.dialogTable = false;
                }else{
                    this.$message({
                        message: '请选择药品',
                        type: 'warning'
                    });
                }
            },
            // 删除
            handleDelete(index){
                this.list.splice(index,1);
                this.amount = countNumPrice(this.list,'appyCnt');
            },
            // 保存
            handleSave(){
                if(this.list.length == 0){
                    this.$message({
                        message: '请添加药品',
                        type: 'warning'
                    });
                }else{
                    this.ssLoad = true;
                    if(this.$route.query.type == 'add'){
                        let data = this.list.map((i)=>{
                            return {'drugListId':i.drugListId,'id':i.id,'appyCnt':i.appyCnt}
                        })
                        let ddAdd = {
                            drugAppyOrdDetlDReqDTOS: data,
                        }
                        console.log(ddAdd,'ddAdd')
                        saveAppy(ddAdd).then((res) => {
                            this.ssLoad = false;
                            this.$router.push('applyManagement')
                        })
                        .catch((err) => {
                            this.ssLoad = false;
                        });
                    }else{
                        let data = this.list.map((i)=>{
                            return {'drugListId':i.drugListId,'id':i.id,'appyCnt':i.appyCnt}
                        })
                        let ddEdit = {
                            id: this.$route.query.id,
                            drugAppyOrdDetlDReqDTOS: data,
                        }
                        console.log(ddEdit,'ddEdit')
                        saveAppy(ddEdit).then((res) => {
                            this.ssLoad = false;
                            this.$router.push('applyManagement')
                        })
                        .catch((err) => {
                            this.ssLoad = false;
                        });
                    }
                }
            },
            // 提交
            handleSubmit(){
                if(this.list.length == 0){
                    this.$message({
                        message: '请添加药品',
                        type: 'warning'
                    });
                }else{
                    this.$confirm("确认提交", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }).then(() => {
                        this.bbLoad = true;
                        if(this.$route.query.type == 'add'){
                            let data = this.list.map((i)=>{
                                return {'drugListId':i.drugListId,'id':i.id,'appyCnt':i.appyCnt}
                            })
                            let ddAdd = {
                                drugAppyOrdDetlDReqDTOS: data,
                            }
                            console.log(ddAdd,'ddAdd')
                            submitAppy(ddAdd).then((res) => {
                                this.bbLoad = false;
                                this.$router.push('applyManagement')
                            })
                            .catch((err) => {
                                this.bbLoad = false;
                            });
                        }else{
                            let data = this.list.map((i)=>{
                                return {'drugListId':i.drugListId,'id':i.id,'appyCnt':i.appyCnt}
                            })
                            let ddEdit = {
                                id: this.$route.query.id,
                                drugAppyOrdDetlDReqDTOS: data,
                            }
                            console.log(ddEdit,'ddEdit')
                            submitAppy(ddEdit).then((res) => {
                                this.bbLoad = false;
                                this.$router.push('applyManagement')
                            })
                            .catch((err) => {
                                this.bbLoad = false;
                            });
                        }
                    })
                }
            },
        },
    }
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__footer{
    text-align: center;
}
::v-deep .long .el-form-item__content{
    width: 220px;
}
</style>