<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="上级分类" prop="sid">
                <el-select v-model="queryParams.sid" filterable clearable placeholder="请选择上级分类" >
                    <el-option
                        v-for="option in options"
                        :label="option.suppliesName"
                        :value="option.id"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="物料名称" prop="detailsName">
                <el-input
                    v-model="queryParams.detailsName"
                    placeholder="请输入物料名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                    maxlength="36"
                />
            </el-form-item>

<!--            <el-form-item label="一级分类名称" prop="oneLevel" label-width="100px">
                <el-select v-model="queryParams.oneLevel" filterable clearable placeholder="请输入一级分类名称">
                    <el-option
                        v-for="option in options1"
                        :label="option.detailsName"
                        :value="option.oneLevel"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="二级分类名称" prop="twoLevel" label-width="100px">
                <el-select v-model="queryParams.twoLevel" filterable clearable placeholder="请输入二级分类名称">
                    <el-option
                        v-for="option in options2"
                        :label="option.detailsName"
                        :value="option.twoLevel"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="三级分类名称" prop="threeLevel" label-width="100px">
                <el-select v-model="queryParams.threeLevel" filterable clearable placeholder="请输入三级分类名称">
                    <el-option
                        v-for="option in options3"
                        :label="option.detailsName"
                        :value="option.threeLevel"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="所属系统" prop="sysclassify">
                <el-input
                    v-model="queryParams.sysclassify"
                    placeholder="请输入所属系统"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                    maxlength="15"
                />
            </el-form-item>-->

            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @keyup.enter.native="handleQuery">
                    <el-option label="启用" :value="0"></el-option>
                    <el-option label="禁用" :value="1"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>

        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['ActSuppliesDetails:ActSuppliesDetails:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['ActSuppliesDetails:ActSuppliesDetails:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['ActSuppliesDetails:ActSuppliesDetails:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['ActSuppliesDetails:ActSuppliesDetails:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="ActSuppliesDetailsList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" width="80" align="center" label="序号" :index="indexMethod" />
            <el-table-column label="上级分类" align="center">
                <template slot-scope="scope">
                    <div>
                        <template>
                            {{ scope.row.fname }}
                        </template>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="物资编码" align="center" prop="code"></el-table-column>
            <el-table-column label="物料名称" align="center" prop="detailsName" />
<!--            <el-table-column label="所属系统" align="center" prop="sysclassify" />-->
            <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                    <div>
                        <el-switch
                            @change="toggleEnable(scope.row)"
                            v-model="scope.row.status"
                            :active-value="0"
                            :inactive-value="1"
                            active-color="#13ce66"
                            inactive-color="#cccccc">
                        </el-switch>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['ActSuppliesDetails:ActSuppliesDetails:edit']"
                    >修改</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['ActSuppliesDetails:ActSuppliesDetails:remove']"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改物料细分类管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="上级分类" prop="sid">
                    <el-select v-model="form.sid" filterable placeholder="请选择所属分类" style="width:380px" >
                        <el-option
                            v-for="option in options"
                            :key="option.suppliesName"
                            :label="option.fname==null ? option.id+'-'+option.suppliesName : option.fname+'-'+option.suppliesName"
                            :value="option.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
<!--                <el-form-item label="分类级别" prop="level">
                    <el-select v-model="form.level" filterable placeholder="请选择要添加的分类级别" >
                        <el-option label="一级分类" :value="1"></el-option>
                        <el-option label="二级分类" :value="2"></el-option>
                        <el-option label="三级分类" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属一级分类" prop="oneLevel" v-if="form.level===2 || form.level ===3">
                    <el-select v-model="form.oneLevel" filterable @change="handleOptionChange(form.oneLevel)" placeholder="请选择所属一级分类" >
                        <el-option
                            v-for="option in options1"
                            :key="option.detailsName"
                            :label="option.detailsName"
                            :value="option.oneLevel"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属二级分类" prop="twoLevel" v-if="form.level===3">
                    <el-select v-model="form.twoLevel" filterable placeholder="请选择所属二级分类" >
                        <el-option
                            v-for="option in options22"
                            :key="option.detailsName"
                            :label="option.detailsName"
                            :value="option.twoLevel"
                        ></el-option>
                    </el-select>
                </el-form-item>-->

<!--                <el-form-item label="物料编码" prop="oneLevel" v-if="form.level===1">
                    <el-input v-model="form.oneLevel" placeholder="请输入一级分类编码" />
                </el-form-item>
                <el-form-item label="物料编码" prop="twoLevel" v-if="form.level===2">
&lt;!&ndash;                    <el-input v-model="form.oneLevel" disabled  maxlength="2" minlength="2" style="width: 80px"/>&ndash;&gt;
                    <el-input v-model="form.twoLevel" placeholder="请输入二级分类编码"  maxlength="4" minlength="2" show-word-limit style="width: 200px"/>
                </el-form-item>
                <el-form-item label="物料编码" prop="threeLevel" v-if="form.level===3">
&lt;!&ndash;                    <el-input v-model="form.twoLevel" disabled  maxlength="2" minlength="2" style="width: 80px"/>&ndash;&gt;
                    <el-input v-model="form.threeLevel" placeholder="请输入三级分类编码" maxlength="6" minlength="2" show-word-limit style="width: 200px"/>
                </el-form-item>-->

                <el-form-item label="物料编码" prop="code" >
                    <el-input v-model="form.code" placeholder="物料编码" maxlength="10"/>
                </el-form-item>
                <el-form-item label="物料名称" prop="detailsName">
                    <el-input v-model="form.detailsName" placeholder="请输入物料名称"  maxlength="36"/>
                </el-form-item>
<!--                <el-form-item label="所属系统" prop="sysclassify">
                    <el-input v-model="form.sysclassify" placeholder="请输入所属系统"  maxlength="36"/>
                </el-form-item>-->
                <el-form-item label="状态" prop="status" >
                    <el-select v-model="form.status" placeholder="请选择状态" style="width:380px">
                        <el-option label="启用" :value="0"></el-option>
                        <el-option label="禁用" :value="1"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleExport123">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listActSuppliesDetails, toggleEnable,toggleDisable,getActSuppliesDetails, delActSuppliesDetails, addActSuppliesDetails, updateActSuppliesDetails, exportActSuppliesDetails, saveSid, getLevel} from "@/api/ActSuppliesDetails/ActSuppliesDetails";

export default {
    name: "ActSuppliesDetails",
    components: {
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            name:[],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 物料细分类管理表格数据
            ActSuppliesDetailsList: [],

            options:[],//初始化空数组

            options1:[],
            options2:[],
            options3:[],
            options22:[],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                sid: null,
                fname:null,
                oneLevel:null,
                twoLevel:null,
                threeLevel:null,
                detailsName: null,
                sysclassify: null,
                status: 0,
            },
            // 表单参数
            form: {
                status:'0'
            },
            // 表单校验
            rules: {
                sid: [
                    { required: true, message: "关联中类不能为空", trigger: "change" }
                ],
                detailsName: [
                    { required: true, message: "物料名称不能为空", trigger: "blur" }
                ],
                sysclassify: [
                    { required: true, message: "所属系统不能为空", trigger: "blur" }
                ],
              /*  oneLevel: [
                    { required: true, message: "一级分类不能为空", trigger: "change" },
                ],
                twoLevel: [
                    { required: true, message: "二级分类不能为空", trigger: "change" },
                ],*/
                /*threeLevel: [
                    { required: true, message: "三级编码不能为空", trigger: "change" },
                ],*/
                level:[
                    { required: true, message: "分类级别不能为空", trigger: "blur" }
                ],
            },
            idRules:[
                { pattern: /^\d+$/, message: 'ID只能输入数字', trigger: 'blur' }
            ]
        };
    },
    created() {
        this.getList();
    },
    mounted() {
        this.fetchOptions();
    },
    methods: {

        handleOptionChange(one){

            for (let i=0,j=0;i<this.options2.length;i++){
                if (this.options2[i].oneLevel===one){
                    this.options22[j] = this.options2[i];
                    j++;
                }
            }

        },

        /**显示序号*/
        indexMethod(index){
            return  index + 1;
        },

        /**启用 */
        toggleEnable(actSuppliesDetails){
            console.log('你点击了【' + actSuppliesDetails.detailsName+'】的开关控件，当前开关值:' + actSuppliesDetails.status);
            let enableText=['启用','禁用'];
            if(actSuppliesDetails.status === 0) {
                toggleEnable(actSuppliesDetails.id).then((response) =>{

                    if(response.code === 200){

                        let message = '操作成功，已经将【' + actSuppliesDetails.detailsName +'】的状态改为【'+ enableText[actSuppliesDetails.status] +'】 !';
                        this.$message({
                            message: message,
                            type:'success'
                        });
                    }else {
                        this.$message.error(response.message);
                    }
                });
            }else {
                toggleDisable(actSuppliesDetails.id).then((response) =>{
                    if(response.msg === "200"){
                        let message = '操作成功，已经将【' + actSuppliesDetails.detailsName +'】的状态改为【'+ enableText[actSuppliesDetails.status] +'】 !';
                        this.$message({
                            message: message,
                            type:'error'
                        });
                    }else {
                        this.$message.error(response.msg);
                    }
                });
            }
        },

        /** 获取上级分类*/
        fetchOptions() {
             saveSid().then(response => {
                this.options = response.rows;

                for (let i=0;i<this.options.length;i++){

                    if (this.options[i].level ===2){

                        for (let j=0;j<this.options.length;j++){

                            if (this.options[j].level ===1 &&this.options[j].oneLevel ===this.options[i].oneLevel){
                                this.options[i].suppliesName = this.options[j].suppliesName+'-'+this.options[i].suppliesName
                            }

                        }

                    }else if (this.options[i].level ===3){


                    }

                }

            });
            getLevel().then(response =>{

                for (let i=0,a=0,b=0,c=0;i<response.rows.length;i++){
                    if (response.rows[i].level === 3){
                        this.options3[a] = response.rows[i];
                        a++;
                    }else if (response.rows[i].level === 2){
                        this.options2[b] = response.rows[i];
                        b++;
                    }else if (response.rows[i].level === 1){
                        this.options1[c] = response.rows[i];
                        c++;
                    }
                }

            });

        },

        /** 查询物料细分类管理列表 */
        getList() {
            this.indexMethod(0);
            this.loading = true;
            listActSuppliesDetails(this.queryParams).then(response => {
                this.ActSuppliesDetailsList = response.rows;
                this.total = response.total;
                this.loading = false;

            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                sid: null,
                detailsName: null,
                sysclassify: null,
                status: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.name = selection.map(item => item.detailsName)
            this.single = selection.length!==1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            debugger
            this.fetchOptions();
            this.reset();
            this.open = true;
            this.title = "新增物料";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getActSuppliesDetails(id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改物料";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateActSuppliesDetails(this.form).then(response => {
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addActSuppliesDetails(this.form).then(response => {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            const name = row.detailsName|| this.name ;
            this.$confirm('是否确认删除物料名称为"' + name  + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function() {
                return delActSuppliesDetails(ids);
            }).then((result) => {
                if (result.msg==="312"){
                    this.getList();
                    this.msgError("删除失败,存在关联关系("+result.data+")");
                }else {
                    this.getList();
                    this.msgSuccess("删除成功");
                }
            }).catch(()=>{
            })
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有六矿物料数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function() {
                return exportActSuppliesDetails(queryParams);
            }).then(response => {
                this.download(response.msg);
            })
        },


        /** 导出设置 */
        handleExport123: debounce(function() {
            // 处理点击事件
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateActSuppliesDetails(this.form).then(response => {
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addActSuppliesDetails(this.form).then(response => {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        }, 1000),
    }
};

function debounce(func, delay) {
    let timer;
    return function () {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            func.apply(context, args);
        }, delay);
    };
}
</script>
