<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true">
                <el-form-item label="供应商列表">
                    
                </el-form-item>
                <el-form-item >
                    <div>
                    <el-input style="float:left;" v-model="keyword" class="input-with-select" placeholder="请输入供应商名称关键字" clearable="true" @clear="getList()">
                        <el-button slot="append" @click="searchList" icon="el-icon-search"></el-button>
                    </el-input>
                    </div>
                </el-form-item>
                <el-form-item style="float:right;">
                    <el-link type="primary" :underline="false" @click="handleAdd(-1,null)" style="margin-right: 10px">新增供应商</el-link>
                    <el-link type="primary" :underline="false" @click="intocustomerRatio" style="margin-right: 10px">批量导入供应商</el-link>
                    <el-link type="primary" :underline="false" @click="showClfDialog = true">分类管理</el-link>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="list" highlight-current-row v-loading="listLoading" :height="tableHeight" style="width: 100%;" @selection-change="selectionChange">
            <el-table-column type="selection" width="60">
                <!-- <template slot-scope="scope" >
                        {{scope.$index+1+(page-1)*size}}
                    </template> -->
            </el-table-column>
            <el-table-column prop="providerCode" label="供应商编码"  width="200"></el-table-column>
            <el-table-column prop="providerName" label="供应商名称" width="200"></el-table-column>
            <el-table-column prop="providerCategoryName" label="供应商分类" width="200"></el-table-column>
            <el-table-column prop="contactName" label="联系人"  width="120"></el-table-column>
            <el-table-column prop="contactPhone" label="联系电话"  width="150"></el-table-column>
            <el-table-column prop="email" label="邮箱"  width="180"></el-table-column>
            <el-table-column prop="address" label="地址" width="200"></el-table-column>
            <el-table-column prop="remark" label="备注" width="300"></el-table-column>
            
            <el-table-column label="操作" width="150" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="handleAdd(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini"  @click="deletePro(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="primary" size="small" @click="batchDelete" :loading="delLoading">批量删除</el-button>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[20 , 50 , 80 , 100]"
                :page-size="20"
                layout="total, sizes, prev, pager, next"
                :total="total"
                style="float:right;"
            ></el-pagination>
        </el-col>

        <!--新增界面-->
        <el-dialog :title="title" v-if="addFormVisible" :visible.sync="addFormVisible" :close-on-click-modal="false" customClass="customWidth" width="800px">
            <el-form ref="form1" :model="addForm" :rules="rules" label-width="120px">
                <el-form-item label="供应商编号" >
                    <el-input v-model="addForm.providerCode" :max="20" placeholder="请输入供应商编号" clearable></el-input>
                </el-form-item>
                <el-form-item label="供应商名称" prop="providerName">
                    <el-input v-model="addForm.providerName" :max="20" placeholder="请输入供应商名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="供应商分类" prop="providerCategoryId">
                    <el-select v-model="addForm.providerCategoryId" filterable placeholder="请选择供应商分类" clearable @change="supplierChange">
                        <el-option v-for="item in baseClfList" :key="item.id" :label="item.providerCategoryName" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="联系人" prop="contactName">
                    <el-input v-model="addForm.contactName" :max="20" placeholder="请输入供应商联系人" clearable></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="addForm.contactPhone" :max="20" placeholder="请输入供应商联系电话" clearable></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email" :max="25" placeholder="请输入供应商邮箱" clearable></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="addForm.address" :max="50"  placeholder="请输入供应商联系地址" clearable></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark ">
                    <el-input type="textarea" :rows="4" v-model="addForm.remark " maxlength="100" show-word-limit placeholder="请输入备注" clearable></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer;">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submitInsert" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
         <!-- 导入结果说明 -->
        <el-dialog title="分摊比例导入结果" v-if="showImportResult" :visible.sync="showImportResult" customClass="customWidth" width="500px">
            <div>
                <span>{{importResultMsg}}</span>
                
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="showImportResult=false">确定</el-button>
            </span>
        </el-dialog>
         <el-dialog title="导入供应商数据" v-if="intocustomerDialog" :visible.sync="intocustomerDialog" customClass="customWidth" width="500px">
            <p>1. 下载
            <el-link type="primary" style="margin-left:5px;" :underline="false" href="./upload/供应商导入模板.xlsx" download="供应商导入模板.xlsx">供应商导入模板.xlsx</el-link>
            </p>
            <!-- <p>2. 填写excel模板,请确保模板中的项目和人员已添加到系统中。</p> -->
            <p style="display: flex;justify-content: center;padding:1em 0">
                <el-upload ref="upload"  action="#" :limit="1" :http-request="batchImportData" :show-file-list="false">
                <el-button type="primary" :underline="false" :loading="importingData">开始导入</el-button>
            </el-upload>
            </p>
        </el-dialog>

        <!-- 分类管理 -->
        <el-dialog title="供应商分类条目管理" show-header="false" v-if="showClfDialog" :visible.sync="showClfDialog" :close-on-click-modal="false" customClass="customWidth" width="500px">
            <el-table :data="baseClfList" highlight-current-row  height="400" style="width: 100%;">
            <el-table-column type="index" width="60" label="序号">
                <template slot-scope="scope" >
                        {{scope.$index+1+(page-1)*size}}
                    </template>
            </el-table-column>
            <el-table-column prop="providerCategoryName" label="名称" ></el-table-column>
            <el-table-column label="操作" width="150">
                <template slot-scope="scope" >
                    <el-button size="small" type="primary" @click="addNewClf(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteClf(scope.row)">删除</el-button>
                </template>
            </el-table-column>

            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="showClfDialog = false" >关闭</el-button>
                <el-button type="primary" @click="addNewClf()" >新增分类项</el-button>
            </div>
        </el-dialog>
        <!-- 新增/编辑 分类条目 -->
        <el-dialog title="新增/修改分类条目" v-if="addClfDialog" :visible.sync="addClfDialog" :close-on-click-modal="false" customClass="customWidth" width="500px">
            <el-form ref="form2" :model="addClf" :rules="rules" label-width="100px">
                <el-form-item label="主项目名称" prop="name">
                    <el-input v-model="addClf.providerCategoryName" placeholder="请输入主项目名称" clearable></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addClfDialog = false">取消</el-button>
                <el-button type="primary" @click="submitClf" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>
<style scoped>
.input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
.line {
    padding:10px;
}
.line span{
    font-size:15px;
}
.line span:nth-child(even){
    float:right;
}
</style>
<script>
    import util from "../../common/js/util";
    export default {
        data() {
            return {
                roleArray:["普通员工","超级管理员", "系统管理员", "公司高层","财务管理员", "项目管理员"],
                status:null,
                statusTxt:["-","进行中","已完成","已撤销"],
                importanceList:[{id:1,label:'正常'},{id:2,label:'紧急'},{id:3,label:'重要'},{id:4,label:'重要且紧急'}],
                searchField:null,
                keyword:null,
                user: JSON.parse(sessionStorage.getItem("user")),
                userDetailVisible: false,
                userDetail:{},
                date: new Date(),
                users: [],
                participator:[],
                tableHeight: 0,
                listLoading: false,
                total: 0,
                page: 1,
                size: 20,
                list: [],
                subProjectVisible: false,
                subProjectList: [],//子项目列表
                currentProject:{},
                addSubProject: false,
                addFormVisible: false,
                addLoading: false,
                addUp: 0, // 合计
                title: "",
                addForm: {
                    name: '',
                    userId: [],
                    level:1,
                },
                rules: {
                    providerName: [{ required: true, message: "请输入供应商名称", trigger: "blur" }],
                },
                intocustomerDialog:false,
                importingData: false,
                importResultMsg:null,
                showImportResult:false,
                selectArr: [],
                delLoading: false,
                showClfDialog: false,
                baseClfList: [],
                addClf: {providerCategoryName: '', companyId: ''},
                addClfDialog: false
            };
        },
        // 过滤器
        filters: {
            numberToCurrency(value) {
                if (!value) return '0.00'
                // 将数值截取，保留两位小数
                value = value.toFixed(2)
                // 获取整数部分
                const intPart = Math.trunc(value)
                // 整数部分处理，增加,
                const intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
                // 预定义小数部分
                let floatPart = '.00'
                // 将数值截取为小数部分和整数部分
                const valueArray = value.toString().split('.')
                if (valueArray.length === 2) { // 有小数部分
                floatPart = valueArray[1].toString() // 取得小数部分
                return intPartFormat + '.' + floatPart
                }
                return intPartFormat + floatPart
            }
        },
        methods: {
            // 新增/编辑 分类条目
            addNewClf(row) {
                this.addClfDialog = true;
                if (row == null) {
                    this.addClf = {}
                } else {
                    this.addClf = row;
                }
            },
            // 删除分类条目
            deleteClf(row) {
                this.$confirm("该操作可能造成已有数据丢失，确定要删除吗?","删除分类条目", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                .then(() => {
                    this.listLoading = true;
                    this.http.post('/provider-category/delete',{ 
                        id: row.id 
                    },
                    res => {
                        this.listLoading = false;
                        if (res.code == "ok") {
                            this.$message({
                                message: "删除成功",
                                type: "success"
                            });
                            this.getClfConfigList();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        this.listLoading = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                     });
                })
                .catch(() => {});
            },
            // 获取分类条目
            getClfConfigList() {
                this.http.get('/provider-category/list',
                res => {
                    if (res.code == "ok") {
                       this.baseClfList = res.data;
                       console.log("获取分类条目",res.data);
                       this.$forceUpdate();
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });  
            },
            supplierChange(e) {
                console.log(this.addForm.providerCategoryId)
                if(this.addForm.providerCategoryId) {
                    for(var i in this.baseClfList) {
                        if(this.baseClfList[i].id == this.addForm.providerCategoryId) {
                            this.addForm.providerCategoryName = this.baseClfList[i].providerCategoryName
                        }
                    }
                } else {
                    this.addForm.providerCategoryName = ''
                }
            },
            // 提交分类
            submitClf() {
                console.log(this.addClf)
                this.http.post('/provider-category/addOrMod',this.addClf,
                    res => {
                        if (res.code == "ok") {
                            this.addClfDialog = false;
                            // this.baseClfList = res.data;
                            this.getClfConfigList()
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
            },
            // 批量删除
            selectionChange(selection){
                console.log('sel',selection);
                this.selectArr = selection
            },
            batchDelete(){
                if(this.selectArr.length == 0){
                    this.$message('请选择要删除的供应商数据')
                    return
                }else{
                    let nametext = ''
                    for(let i in this.selectArr){
                        nametext += this.selectArr[i].providerName + '、'
                    }
                    nametext = nametext.substring(0,nametext.length - 1)
                    this.$confirm("确定要批量删除供应商：" + nametext + "\u3000吗?","删除供应商", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }).then(()=>{
                        this.delLoading = true
                        let batchIds = ''
                        for(let m in this.selectArr){
                            batchIds += this.selectArr[m].id + ','
                        }
                        batchIds = batchIds.substring(0,batchIds.length - 1)
                        this.http.post('/provider-info/batchDelete',{
                            batchIds
                        },res => {
                            this.delLoading = false
                            if(res.code == 'ok'){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                })
                                this.getList()
                            }else {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                })
                            }
                        },err => {
                            this.delLoading = false
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            })
                        })
                    })
                    
                }
            },
            intocustomerRatio(){
                this.intocustomerDialog=true;
            },
            batchImportData(item) {
                //首先判断文件类型
                let str = item.file.name.split(".");
                let format = str[str.length - 1];
                if (format != "xls" && format != "xlsx") {
                    this.$message({
                        message: "请选择.xls或.xlsx文件",
                        type: "error"
                    });
                } else {
                    this.importingData = true;
                    let formData = new FormData();
                    formData.append("file", item.file);
                    this.http.uploadFile('/provider-info/importData', formData,
                    res => {
                        this.$refs.upload.clearFiles();
                        this.importingData = false;
                        this.showImportResult = true;
                        if (res.code == "ok") {
                            //换成弹出框，以免有人等了半天回来啥也没看到
                            this.importResultMsg = "成功导入/更新"+res.data+"条供应商数据。"+(res.msg?res.msg:"");
                            this.getList();
                        } else {
                            this.importResultMsg = "导入失败："+res.msg;
                        }
                    },
                    error => {
                        this.$refs.upload.clearFiles();
                        this.importingData = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
                }
            },
            importProject(item) {
                //首先判断文件类型
                let str = item.file.name.split(".");
                let format = str[str.length - 1];
                if (format != "xls" && format != "xlsx") {
                    this.$message({
                        message: "请选择.xls或.xlsx文件",
                        type: "error"
                    });
                } else {
                    this.listLoading = true;
                    let formData = new FormData();
                    formData.append("file", item.file);
                    formData.append("userId", this.user.id);
                    this.http.uploadFile('/project/importData', formData,
                    res => {
                        this.$refs.upload.clearFiles();
                        this.listLoading = false;
                        if (res.code == "ok") {
                            this.$message({
                                message: "导入成功",
                                type: "success"
                            });
                            this.getList();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        this.$refs.upload.clearFiles();
                        this.listLoading = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
                }
            },
            number(){　　
        // 　　　  this.addForm.budget = this.addForm.budget.replace(/[^\.\d]/g,'');
        //         this.addForm.budget = this.addForm.budget.replace('.','');
        　　},
            deleteSubPro(subProject) {
                this.$confirm("确定要删除子项目" + subProject.name + "吗?","删除子项目", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                .then(() => {
                    this.listLoading = true;
                    this.http.post('/sub-project/deleteProject',{ 
                        id: subProject.id 
                    },
                    res => {
                        this.listLoading = false;
                        if (res.code == "ok") {
                            this.$message({
                                message: "删除成功",
                                type: "success"
                            });
                            this.subProject(this.currentProject);
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        this.listLoading = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                        }
                    );
                })
                .catch(() => {});
            },
            searchList() {
                this.page = 1;
                this.getList();
            },
            addNewSubProject(subProject) {
                console.log(123);
                if (subProject == null) {
                    this.addForm = {projectId: this.currentProject.id, level:1}
                } else {
                    this.addForm = subProject;
                }
                this.addSubProject = true;
            },
            //显示子项目
            subProject(item) {
                this.subProjectVisible = true;
                this.currentProject = item;
                this.http.post('/sub-project/list', {
                    projectId: item.id
                },
                res => {
                    if (res.code == "ok") {
                        this.subProjectList = res.data;
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            //显示用户详情
            showUser(userId) {
                this.userDetailVisible = true;
                this.http.post(this.port.manage.userDetail, {
                    userId: userId
                },
                res => {
                    if (res.code == "ok") {
                        this.userDetail = res.data;
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            
            
            //分页
            handleCurrentChange(val) {
                this.page = val;
                this.getList();
            },

            handleSizeChange(val) {
                this.size = val;
                this.getList();
            },

            //获取项目列表
            getList() {
                this.listLoading = true;
                this.http.post('/provider-info/list', {
                    pageIndex: this.page,
                    pageSize: this.size,
                    keyword:this.keyword
                },
                res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        var list = res.data.records;
                        this.list = list;
                        this.total = res.data.total;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },

            //显示新增界面
            handleAdd(i, item) {
                if(i == -1) {
                    this.title = "新增供应商";
                    this.addForm = {
                    }
                } else {
                    this.title = "修改供应商";
                    this.addForm = JSON.parse(JSON.stringify(item));
                }
                this.addFormVisible = true;
            },

            submitInsert() {
                this.$refs.form1.validate(valid => {
                    if (valid) {
                        this.addLoading = true;
                        this.http.post('/provider-info/addOrMod', this.addForm,
                        res => {
                            this.addLoading = false;
                            if (res.code == "ok") {
                                this.addFormVisible = false;
                                this.getList();
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: "error"
                                });
                            }
                        },
                        error => {
                            this.addLoading = false;
                            this.$message({
                                message: error,
                                type: "error"
                            });
                        });
                        }
                });
            },

            // 删除
            deletePro(i, item) {
                this.$confirm("确定要删除供应商" + item.providerName + "吗?","删除供应商", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                .then(() => {
                    this.listLoading = true;
                    this.http.post('/provider-info/delete',{ 
                        id: item.id 
                    },
                    res => {
                        this.listLoading = false;
                        if (res.code == "ok") {
                            this.$message({
                                message: "删除成功",
                                type: "success"
                            });
                            this.getList();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        this.listLoading = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                        }
                    );
                })
                .catch(() => {});
            },
        },
        created() {
            let height = window.innerHeight;
            this.tableHeight = height - 195;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 195;
            };
        },
        mounted() {
            this.getClfConfigList()
            this.getList()
        }
    };
</script>

<style lang="scss" scoped>
.rg_span{
    display: inline-block;
}
.rg_span span {
    text-align: right;
    box-sizing: border-box;
    padding-right: 10px;
}
.el-dialog__title {
    display: inline-table;
    margin-top: 20px;
}
</style>