<template>
    <div>
        <el-card>
            <el-form :inline="true" :model="query" class="query-form" size="mini">
                <el-form-item class="query-form-item">
                    <el-input
                        v-model="query.key"
                        clearable
                        placeholder="关键字搜索"
                        style="width: 400px"
                    ></el-input>
                </el-form-item>
                <el-form-item class="query-form-item">
                    <el-select v-model="query.advanceType" placeholder="请选择仓库类型" clearable>
                        <el-option label="全部" value=""></el-option>
                        <el-option label="寄售" value=true></el-option>
                        <el-option label="仓库" value=false></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="query-form-item">
                    <el-select v-model="query.thirdSysFk" placeholder="请选择第三方系统"
                               @change="thirdSysFkChange(query.thirdSysFk)">
                        <el-option
                            v-for="item in thirdSys"
                            :key="item.thirdId"
                            :label="item.thirdName"
                            :value="item.thirdName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button-group>
                        <el-button type="primary" icon="el-icon-refresh" @click="onReset"></el-button>
                        <el-button type="primary" icon="search" @click="getList">查询</el-button>
                        <el-button type="primary" @click.native="handleForm(null, null,'addTop')"
                                   :disabled="!configParms.basicThirdInv"
                        >添加仓库
                        </el-button>
                    </el-button-group>
                </el-form-item>
            </el-form>
            <el-table
                :data="mergeList"
                style="width: 100%;margin-bottom: 20px;"
                row-key="id"
                border
                default-expand-all
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                <el-table-column type="index" label="序号" width="50"></el-table-column>
                <el-table-column
                    prop="code"
                    label="仓库编码"
                >
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="仓库名称"
                >
                </el-table-column>
                <el-table-column
                    prop="advanceType"
                    label="仓库类型">
                    <template slot-scope="scope">
                        <span>{{ enableMap[scope.row.advanceType] }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="thirdName" label="第三方系统名称">
                    <template slot-scope="scope">
                        <span>{{ getThirdSysFkName(scope.row.thirdSysFk) }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" fixed="right">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="small"
                            :disabled="!configParms.basicThirdInv"
                            @click.native.stop="handleForm(node, scope.row, 'edit')"
                        >编辑
                        </el-button
                        >
                        <el-button
                            type="text"
                            size="small"
                            :disabled="!configParms.basicThirdInv"
                            @click.native.stop="handleDel(node,scope.row)"
                        >删除
                        </el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

        </el-card>
        <el-pagination
            :page-size="query.limit"
            @current-change="handleCurrentChange"
            layout="prev, pager, next"
            :total="total"
        >
        </el-pagination>
        <!--表单界面-->
        <el-dialog
            :title="formMap[formName]"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :visible.sync="subFormVisible"
            :before-close="hideForm"
            width="40%"
            top="5vh"
        >
            <el-form :model="formData" :rules="formRules" ref="dataForm">
                <el-form-item label="本企业仓库" prop="pid">
                    <el-select v-model="formData.pid" placeholder="顶级" disabled>
                        <el-option
                            v-for="item in mergeList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        >
                          <span style="float: left"
                          ><span v-html="item.html"></span>{{ item.name }}</span
                          >
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="仓库编码" prop="title" class="query-form-item">
                    <el-input
                        v-model="formData.code" style="width: 80%"
                        auto-complete="off"
                    ></el-input>
                </el-form-item>
                <el-form-item label="仓库名称" prop="name" class="query-form-item">
                    <el-input
                        v-model="formData.name" style="width: 80%"
                        auto-complete="off"
                    ></el-input>
                </el-form-item>


                <el-form-item class="query-form-item" label="仓库类型:">
                    <el-select v-model="formData.advanceType" placeholder="仓库类型" clearable>
                        <el-option label="寄售" :value=true></el-option>
                        <el-option label="仓库" :value=false></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态:" prop="status" class="query-form-item">
                    <el-radio-group v-model="formData.status">
                        <el-radio :label="0">禁用</el-radio>
                        <el-radio :label="1">正常</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="hideForm">取消</el-button>
                <el-button
                    type="primary"
                    @click.native="formSubmit()"
                    :loading="formLoading"
                >提交
                </el-button
                >
            </div>
        </el-dialog>
        <el-dialog
            :title="formMap[formName]"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :visible.sync="formVisible"
            :before-close="hideForm"
            width="40%"
            top="5vh"
        >
            <el-form :model="formData" :rules="formRules" ref="dataForm">

                <el-form-item label="仓库编码" prop="title" class="query-form-item">
                    <el-input
                        v-model="formData.code" style="width: 80%"
                        auto-complete="off"
                    ></el-input>
                </el-form-item>
                <el-form-item label="仓库名称" prop="name" class="query-form-item">
                    <el-input
                        v-model="formData.name" style="width: 80%"
                        auto-complete="off"
                    ></el-input>
                </el-form-item>


                <el-form-item class="query-form-item" label="仓库类型:">
                    <el-select v-model="formData.advanceType" placeholder="仓库类型" clearable>
                        <el-option label="寄售" :value='true'></el-option>
                        <el-option label="仓库" :value='false'></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="query-form-item" prop="thirdSysFk" label="第三方系统:">
                    <el-select v-model="formData.thirdSysFk" placeholder="请选择第三方系统" clearable>
                        <el-option
                            v-for="item in thirdSys"
                            :key="item.thirdId"
                            :lable="item.thirdName"
                            :value="item.thirdName"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态:" prop="status" class="query-form-item">
                    <el-radio-group v-model="formData.status">
                        <el-radio :label="0">禁用</el-radio>
                        <el-radio :label="1">正常</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="hideForm">取消</el-button>
                <el-button
                    type="primary"
                    @click.native="formSubmit()"
                    :loading="formLoading"
                >提交
                </el-button
                >
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    filterThrList,
    saveThrWarehouse,
    deleteThrWarehouse,
} from "../../api/thrsys/thrInvWarehouse";
import {getBasicThirdSys} from "../../api/basic/basicThirdSys";
import {findConfig} from "@/api/thrsys/spsSyncStatus";

const formJson = {
    id: null,
    pid: null,
    name: null,
    code: null,
    status: 1,
    advanceType: false,
    isDefault: false,
    page: 1,
    limit: 20,
};
export default {
    data() {
        return {
            query: {
                id: null,
                pid: null,
                name: null,
                code: null,
                status: null,
                advanceType: null,
                isDefault: null,
                page: 1,
                limit: 20,
            },
            mergeList: [],
            node: null,
            defaultProps: {
                children: "children",
                label: "name"
            },
            total: 0,
            treeList: [],
            loading: true,
            index: null,
            formName: null,
            formMap: {
                addTop: "添加仓库",
                add: "添加货位",
                edit: "编辑"
            },
            enableMap: {
                true: "寄售",
                false: "仓库",
            },
            formLoading: false,
            subFormVisible: false,
            formVisible: false,
            formData: formJson,
            formRules: {
                name: [
                    {required: true, message: "请输入仓库货位名", trigger: "blur"}
                ],
                code: [
                    {required: true, message: "请输入仓库货位代码", trigger: "blur"}
                ],
                thirdSysFk: [
                    {required: true, message: "请选择第三方系统", trigger: "blur"}
                ]
            },
            pidData: {},
            deleteLoading: false,
            thirdSys: [],
            configParms: {},
        };
    },
    methods: {


        handleCurrentChange(val) {
            this.query.page = val;
            this.getList();
        },
        renderContent(h, {node, data, store}) {
            return (
                <span
                    style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
                    <span>
                    <span title={data.name} style="margin-left:8px">{node.label}</span>
                       <span style="margin-left:18px">(编码：{data.code})</span>
                    </span>
                    <span>

                <el-button
                    style="font-size: 12px;"
                    type="text"
                    on-click={() => this.handleForm(node, data, "edit")}
                >
                编辑
                </el-button>
                <el-button
                    style="font-size: 12px;"
                    type="text"
                    on-click={() => this.handleDel(node, data)}
                >
                删除
                </el-button>
                </span>
                </span>
            );
        },
        onReset() {
            this.$router.push({
                path: "",
            });
            this.query = {
                name: "",
                status: "",
                thirdSysFk: null
            };
            this.getList();
        },
        onSubmit() {
            this.getList();
        },
        getList() {
            this.loading = true;
            if (this.query.thirdSysFk != null) {
                this.getQueryThirdSysFk(this.query.thirdSysFk);
            }
            filterThrList(this.query)
                .then((response) => {
                    this.loading = false;
                    this.mergeList = response.data.list || [];
                    this.total = response.data.total || 0;
                    this.treeList = response.data.tree_list || [];
                    this.getQueryThirdSysFkName(this.query.thirdSysFk);
                })
                .catch(() => {
                    this.loading = false;
                    this.mergeList = [];
                    this.total = 0;
                    this.treeList = [];
                });
        },
        getQueryThirdSysFk() {
            this.thirdSys.forEach((item) => {
                if (item.thirdName == this.query.thirdSysFk) {
                    this.query.thirdSysFk = item.thirdId;
                }
            })
        },
        getQueryThirdSysFkName() {
            this.thirdSys.forEach((item) => {
                if (item.thirdId == this.query.thirdSysFk) {
                    this.query.thirdSysFk = item.thirdName;
                }
            })
        },
        getThirdSysFkName(thirdSys) {
            for (let i = 0; i < this.thirdSys.length; i++) {
                if (this.thirdSys[i].thirdId === thirdSys) {
                    return this.thirdSys[i].thirdName;
                }
            }
        },
        // 刷新表单
        resetForm() {
            if (this.$refs["dataForm"]) {
                // 清空验证信息表单
                this.$refs["dataForm"].clearValidate();
                // 刷新表单
                this.$refs["dataForm"].resetFields();
                this.getList();
            }
        },
        // 隐藏表单
        hideForm() {
            // 更改值
            this.formVisible = false;
            this.subFormVisible = false;
            return true;
        },
        // 显示表单
        handleForm(node, data, formName) {
            this.formVisible = true;
            let no = Math.floor(Math.random() * 10000000)
            this.pidData = data || null;
            formJson.pid = (data && parseInt(data.id)) || "";
            this.formData = JSON.parse(JSON.stringify(formJson));
            if (formName === "edit") {
                this.formData = Object.assign({}, data);
                if (this.formData.thirdSysFk != null) {
                    this.thirdSys.forEach((item) => {
                        if (item.thirdId == this.formData.thirdSysFk) {
                            this.formData.thirdSysFk = item.thirdName;
                        }
                    })
                }
                this.node = node;
            } else {
                this.formData.code = no;
            }

            this.formData.pid = !this.formData.pid ? "" : this.formData.pid;
            this.formName = formName;
            if (data && data.id) {
                this.index = this.mergeList.findIndex((d) => d.id === data.id);
            }
        },

        handleSubForm(node, data, formName) {
            this.subFormVisible = true;

            this.pidData = data || null;
            formJson.pid = (data && parseInt(data.id)) || "";
            this.formData = JSON.parse(JSON.stringify(formJson));
            if (formName === "edit") {
                this.formData = Object.assign({}, data);
                this.node = node;
            } else {
                let no = this.getProjectNum() + Math.floor(Math.random() * 10000);
                this.formData.code = no;
            }
            this.formData.pid = !this.formData.pid ? "" : this.formData.pid;

            this.formName = formName;
            if (data && data.id) {
                this.index = this.mergeList.findIndex((d) => d.id === data.id);
            }
        },
        formSubmit() {
            this.$refs["dataForm"].validate((valid) => {
                if (valid) {
                    this.formLoading = true;
                    this.thirdSys.forEach((item) => {
                        if (this.formData.thirdSysFk == item.thirdName) {
                            this.formData.thirdSysFk = item.thirdId;
                        }
                    });
                    let data = Object.assign({}, this.formData);
                    saveThrWarehouse(data, this.formName)
                        .then((response) => {
                            this.formLoading = false;
                            if (response.code !== 20000) {
                                this.$message.error(response.message);
                                return false;
                            }
                            this.$message.success("操作成功");

                            this.formVisible = false;
                            if (this.formName !== "edit") {
                                if (response.data && response.data.id) {
                                    data.id = response.data.id;
                                    if (this.pidData) {
                                        if (!this.pidData.children) {
                                            this.$set(this.pidData, "children", []);
                                        }
                                        this.pidData.children.push(data);
                                    } else {
                                        this.mergeList.push(data);
                                    }
                                }
                            } else {
                                // const parent = this.node.parent;
                                // const children = parent.data.children || parent.data;
                                // const index = children.findIndex((d) => d.id === data.id);
                                // children.splice(index, 1, data);
                            }
                            // 刷新表单
                            this.resetForm();
                            this.getList();
                        })
                        .catch(() => {
                            this.formLoading = false;
                        });
                }
            });
        },
        // 删除
        handleDel(node, data) {
            if (data.children && data.children.length > 0) {
                this.$alert("请先删除子节点", "提示", {
                    confirmButtonText: "确定",
                });
                return false;
            }
            if (data.id) {
                this.$confirm("确认删除该记录吗?", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        this.deleteLoading = true;
                        let para = {id: data.id};
                        deleteThrWarehouse(para)
                            .then((response) => {
                                this.deleteLoading = false;
                                if (response.code !== 20000) {
                                    this.$message.error(response.message);
                                    return false;
                                }
                                this.$message.success("删除成功");
                                this.getList();
                                const parent = node.parent;
                                const children = parent.data.children || parent.data;
                                const index = children.findIndex((d) => d.id === data.id);
                                children.splice(index, 1);
                            })
                            .catch(() => {
                                this.deleteLoading = false;
                            });
                    })
                    .catch(() => {
                        this.$message.info("取消删除");
                    });
            }
        },
        getProjectNum() {
            const projectTime = new Date() // 当前中国标准时间
            const Year = projectTime.getFullYear() // 获取当前年份 支持IE和火狐浏览器.
            const Month = projectTime.getMonth() + 1 // 获取中国区月份
            const Day = projectTime.getDate() // 获取几号
            var CurrentDate = Year
            if (Month >= 10) { // 判断月份和几号是否大于10或者小于10
                CurrentDate += Month
            } else {
                CurrentDate += '0' + Month
            }
            if (Day >= 10) {
                CurrentDate += Day
            } else {
                CurrentDate += '0' + Day
            }
            return CurrentDate
        },
        getBasicThirdSys() {
            let query = {
                enabled: true,
            };
            getBasicThirdSys(query)
                .then((response) => {
                    this.thirdSys = response.data.list || [];
                })
                .catch(() => {
                    this.loading = false;
                    this.list = [];
                });
        },
        thirdSysFkChange(thirdSysFk) {
            console.log(thirdSysFk);
        },
        getSyncConfig() {
            findConfig()
                .then((response) => {
                    if (response.code == 20000) {
                        this.configParms = response.data;
                    }
                })
                .catch(() => {
                });
        },
    },
    filters: {
        statusFilterType(status) {
            const statusMap = {
                0: "gray",
                1: "success",
            };
            return statusMap[status];
        },
        statusFilterName(status) {
            const statusMap = {
                0: "禁用",
                1: "正常",
            };
            return statusMap[status];
        },
    },
    mounted() {
    },
    created() {
        // 加载表格数据
        this.getBasicThirdSys();
        this.getSyncConfig();
        this.getList();
    },
};
</script>

<style type="text/scss" lang="scss">
</style>
