import { listStationConsumable } from "@/api/system/stationConsumable";
import stationAcatar from "../stationAvatar/index.vue";
import {
    listInfo,
} from "@/api/system/classifyItem.js";
import {
    list,
    getNurseItem,
    delNurseItem,
    addNurseItem,
    updateNurseItem,
    updatePicture,
    updateShelfStatus
} from "@/api/system/nurseItem";
import { getToken } from "@/utils/auth";
import { getListByUser } from "@/api/system/userlist.js";

export default {
    components: { stationAcatar },
    name: "NurseItem",
    data() {
        return {
            // 弹出层判断新增还是修改
            isEditFlag: false,
            imgsurl: { pictureUrlList: [] },
            imageUrl: "",
            imgone: "",
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/system/stationItem/importData",
            },
            // 遮罩层
            loading: true,
            stationConsumableshow: false,
            nurseStationshow: false,
            Classifyshow: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            total2: 0,
            total3: 0,
            total4: 0,
            //耗材
            stationConsumableList: [],
            // 护理站护理项目表格数据
            nurseItemList: [],
            //护理站类型表
            typelist: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            options: [{
                    value: 'HALF_HOUR',
                    label: '半小时'
                }, {
                    value: 'ONE_HOUR',
                    label: '一小时'
                },
                {
                    value: 'NINETY_MINUTES',
                    label: '九十分钟'
                },
                {
                    value: 'TWO_HOUR',
                    label: '两小时'
                }

            ],
            value: "",
            optionlist: [{
                value: 'HALF_DAY',
                label: '半天'
            }, {
                value: 'ONE_DAY',
                label: '一天'
            }, ],
            value1: "",
            //权限查询
            nurseStationlist: [],
            nurseStationlist2: [],
            getListByUserquery: {
                pageNum: 1,
                pageSize: 10,
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                nurseStationId: null,
                nurseTypeId: null,
                userId: null,
                nurseItemCode: null,
                nurseItemName: null,
                nurseItemContent: null,
                advanceAppointDuration: null,
                sort: null,
            },
            // 查询参数
            StationConsumablequeryParams: {
                pageNum: 1,
                pageSize: 10,
                nurseStationId: null,
                consumableDetail: null,
            },
            // 表单参数
            form: {
                nurseStationItem: {
                    nurseStationId: null,
                    nurseTypeId: null,
                    nurseItemName: null,
                    nurseItemContent: null,
                    advanceAppointDuration: null,
                    itemPictureUrl: null,
                    sort: null,
                    nurseStationName: "请选择所属护理站",
                    classifyName: '请选择护理项目分类',
                    nurseClassifyId: null,
                    appointmentLimitCount: null,
                    appointmentTimeInterval: null,
                },
            },
            idd: 1,
            // 表单校验
            rules: {
                "nurseStationItem.nurseItemName": [
                    { required: true, message: "护理项目名称不能为空", trigger: "blur" },
                ],
                "nurseStationItem.classifyName": [
                    { required: true, message: "护理项目分类不能为空", trigger: "blur" },
                ],
                "nurseStationItem.nurseStationName": [
                    { required: true, message: "护理项目分类不能为空", trigger: "blur" },
                ],
                "nurseStationItem.nurseItemContent": [
                    { required: true, message: "项目内容简介不能为空", trigger: "blur" },
                ],
                "nurseStationItem.sort": [
                    { required: true, message: "排序不能为空", trigger: "blur" },
                ],
                // "nurseStationItem.advanceAppointDuration": [
                //     { required: true, message: "提前预约时长不能为空", trigger: "blur" },
                // ],
                // }, ],
                "nurseStationItem.appointmentTimeInterval": [{
                    required: true,
                    trigger: "blur",
                    message: "请选择预约时间点间隔",
                }, ],
                "nurseStationItem.itemPictureUrl": [{
                    required: true,
                    trigger: "blur",
                    message: "请选择项目头像",
                }, ],
                // "nurseStationItem.appointmentLimitCount": [{
                //     required: true,
                //     trigger: "blur",
                //     message: "请输入预约人数上限",
                nurseStationId: [
                    { required: true, trigger: "blur", message: "请选择所属护理站" },
                ],
                nurseTypeId: [
                    { required: true, message: "请选择护理类型", trigger: "blur" },
                ],
            },
            homenumber: null,
            stationid: null,
            addxg: null,
            classifyquery: {
                pageNum: 1,
                pageSize: 10,
                classifyCode: null,
                classifyName: null,
            },
            classifylist: [],
            classifytotal: 0,
        };
    },
    created() {
        this.getList();
        this.classifylistInfo();
    },
    methods: {
        commissionAmountinput(e) {
            e.commissionRate = null
        },
        commissionRateoninput(e) {
            e.commissionAmount = null
        },
        //点击上架
        upwhetherShelf(row) {
            let shelfStatus = null
            if (row.shelfStatus == false) {
                shelfStatus = 'NOT_SHELF'
            } else if (row.shelfStatus == true) {
                shelfStatus = 'SHELF'
            }
            updateShelfStatus(row.id, shelfStatus).then((res) => {
                if (row.shelfStatus == false) {
                    this.$modal.msgSuccess("已修改上架状态为未上架");
                } else {
                    this.$modal.msgSuccess("已修改上架状态为上架");
                }
                this.getList();
            });
        },
        //// //护理项目list
        //打开遮罩层
        clickClassifyshow() {
            this.Classifyshow = true
            this.classifylistcancel()
        },
        //关闭遮罩层
        cancelClassifyshow() {
            this.Classifyshow = false
        },
        //选中或者取消选中
        choiceclassify(e) {
            if (this.form.nurseStationItem.nurseClassifyId == e.id) {
                this.form.nurseStationItem.nurseClassifyId = null
                this.form.nurseStationItem.classifyName = null
            } else {
                this.form.nurseStationItem.nurseClassifyId = e.id;
                this.form.nurseStationItem.classifyName = e.classifyName;
            }
            this.Classifyshow = false
        },
        //重置
        classifylistcancel() {
            this.classifyquery = {
                pageNum: 1,
                pageSize: 10,
                classifyCode: null,
                classifyName: null,
            }
            this.classifylistInfo();
        },
        //搜索
        classifylistInfo() {
            listInfo(this.classifyquery).then(res => {
                this.classifylist = res.rows
                this.classifytotal = res.total
            })
        },
        imgs(item) {
            this.imgsurl.pictureUrlList.push(item);
        },
        imgUrl(imgUrl) {

            this.form.nurseStationItem.itemPictureUrl = imgUrl;
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download(
                "/system/stationItem/downloadTemplate?fileType=1", {},
                `护理站项目信息导入模板.xlsx`
            );
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
                response.msg +
                "</div>",
                "导入结果", { dangerouslyUseHTMLString: true }
            );
            this.getList();
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        //耗材包选择完成
        stationConsumablechoiceok() {
            this.form.nurseStationItemConsumables.forEach((e) => {
                e.nurseStationConsumableId = e.id;
            });
            this.stationConsumableshow = false;
        },
        //删除已经选择的耗材包
        delConsumable(item) {
            this.form.nurseStationItemConsumables =
                this.form.nurseStationItemConsumables.filter((e) => e.id != item.id);
        },
        //双击耗材包
        cellchoiceConsumable(item) {
            if (this.form.nurseStationItemConsumables.find((e) => e.id == item.id)) {
                this.form.nurseStationItemConsumables =
                    this.form.nurseStationItemConsumables.filter((e) => e.id != item.id);
            } else {
                this.form.nurseStationItemConsumables.push(item);
            }
        },
        //选择耗材宝
        choiceConsumable(item) {
            this.form.nurseStationItemConsumables.push(item);
        },
        //页面所属护理站
        ParamsStation(item) {
            this.info();
            this.nurseStationshow = true
            this.homenumber = item
            this.stationid = this.queryParams.nurseStationId;
        },
        //打开护理站列表
        nurseStationshowclick() {
            this.stationcancel();
            this.stationid = this.form.nurseStationItem.nurseStationId
            this.nurseStationshow = true
        },
        //护理站页面选择护理站
        choicestationid(item) {
            if (this.homenumber) {
                this.queryParams.nurseStationName = item.nurseStationName;
                this.queryParams.nurseStationId = item.id;
            } else {
                this.stationid = item.id
                this.form.nurseStationItem.nurseStationId = item.id;
                this.form.nurseStationItem.nurseStationName = item.nurseStationName;
                this.StationConsumablequeryParams.nurseStationId = item.id;
            }
            this.nurseStationshow = false;
            this.stationcancel();
        },
        //关闭护理站页面
        clicknurseStationshow() {
            this.nurseStationshow = false;
        },
        //耗材包关闭
        clickstationConsumableshow() {
            this.listStationConsumableinfocancel();
            this.stationConsumableshow = false;
        },
        // 耗材重置
        listStationConsumableinfocancel() {
            this.StationConsumablequeryParams.consumableDetail = null;
            this.StationConsumablequeryParams.pageNum = 1;
            this.StationConsumablequeryParams.pageSize = 10;
            this.listStationConsumable();
        },
        //护理站重置
        stationcancel() {
            this.getListByUserquery = {
                pageNum: 1,
                pageSize: 10,
            };
            this.info();
        },
        /** 耗材列表 */
        listStationConsumable() {
            listStationConsumable(this.StationConsumablequeryParams).then(
                (response) => {
                    this.stationConsumableList = response.rows;
                    this.total3 = response.total;
                }
            );
        },
        listStationConsumableinfo() {
            if (this.form.nurseStationItem.nurseStationId != null) {
                listStationConsumable(this.StationConsumablequeryParams).then(
                    (response) => {
                        this.stationConsumableList = response.rows;
                        this.total3 = response.total;
                        this.stationConsumableshow = true;
                    }
                );
            } else {
                this.$message.error("请先选择护理站");
            }
        },
        /** 查询护理站护理项目列表 */
        getList() {
            this.loading = true;
            list(this.queryParams).then((response) => {
                response.rows.forEach(e => {
                    if (e.shelfStatus == 'SHELF') {
                        e.shelfStatus = true
                    } else {
                        e.shelfStatus = false
                    }
                })
                this.nurseItemList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        //护理站list
        info() {
            getListByUser(this.getListByUserquery).then((res) => {
                this.nurseStationlist = res.rows;
                this.total4 = res.total;
            });
        },
        // 取消按钮
        cancel() {
            var obj = { pictureUrlList: [] };
            if (this.imgone != this.form.nurseStationItem.itemPictureUrl) {
                obj.pictureUrlList.push(this.form.nurseStationItem.itemPictureUrl);
            }
            if (obj.pictureUrlList.length > 0) {
                updatePicture(obj).then((res) => {});
            }
            if (this.imgsurl.pictureUrlList.length > 0) {
                updatePicture(this.imgsurl).then((res) => {});
            }
            this.imgsurl = { pictureUrlList: [] };

            this.open = false;
            this.reset();
        },
        //时长价格
        addnurseStationItemPrices(item, index) {
            if (this.form.nurseStationItemPrices.length == 5) {
                this.$message.error("最多只能5条");
            } else {
                this.idd++;
                var obj = {
                    serveDurationUnit: "",
                    price: "",
                    description: "",
                    idd: this.idd,
                    commissionAmount: "",
                    commissionRate: ""
                };
                this.form.nurseStationItemPrices.push(obj);
            }
        },
        delnurseStationItemPrices(item) {
            if (item.idd && !item.nurseItemPriceId) {
                if (this.form.nurseStationItemPrices.length == 1) {
                    this.$message.error("最后一条不可删除");
                } else {
                    this.form.nurseStationItemPrices =
                        this.form.nurseStationItemPrices.filter((e) => e.idd != item.idd);
                }
            } else if (!item.idd && item.nurseItemPriceId) {
                if (this.form.nurseStationItemPrices.length == 1) {
                    this.$message.error("最后一条不可删除");
                } else {
                    this.form.nurseStationItemPrices =
                        this.form.nurseStationItemPrices.filter(
                            (e) => e.nurseItemPriceId != item.nurseItemPriceId
                        );
                }
            }
        },
        // 表单重置
        reset() {
            this.form = {
                nurseStationItem: {
                    nurseStationId: null,
                    nurseTypeId: null,
                    nurseItemName: null,
                    nurseItemContent: null,
                    advanceAppointDuration: null,
                    itemPictureUrl: null,
                    sort: null,
                    nurseStationName: "请选择所属护理站",
                    classifyName: '请选择护理项目分类',
                    nurseClassifyId: null,
                    appointmentLimitCount: null,
                },
                nurseStationItemConsumables: [
                    // {
                    //   nurseStationConsumableId: "",
                    //   consumableCount: "",
                    //   consumablePrice: "",
                    // },
                ],
                nurseStationItemPrices: [{
                    serveDurationUnit: null,
                    price: null,
                    description: null,
                    idd: this.idd,
                    commissionAmount: "",
                    commissionRate: ""
                }, ],
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                nurseStationId: null,
                nurseTypeId: null,
                userId: null,
                nurseItemCode: null,
                nurseItemName: null,
                nurseItemContent: null,
                advanceAppointDuration: null,
                sort: null,
            };
            this.stationid = null
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.isEditFlag = false;
            this.addxg = 'add'
            this.homenumber = null;
            this.reset();
            this.open = true;
            this.StationConsumablequeryParams.nurseStationId = null;
            this.title = "添加护理站护理项目";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.isEditFlag = true;
            this.addxg = 'xg';
            this.homenumber = null;
            this.reset();
            this.StationConsumablequeryParams.nurseStationId = null;
            const id = row.id || this.ids;
            getNurseItem(id).then((response) => {
                this.form = response.data;
                if (response.data.nurseStationItemConsumables) {
                    response.data.nurseStationItemConsumables.forEach(e => {
                        e.id = e.nurseStationConsumableId
                    })
                } else {
                    response.data.nurseStationItemConsumables = []
                }
                this.StationConsumablequeryParams.nurseStationId =
                    response.data.nurseStationItem.nurseStationId;
                this.imgone = this.form.nurseStationItem.itemPictureUrl;
                if (this.form.nurseStationItemPrices.length <= 0) {
                    var obj = {
                        serveDurationUnit: "",
                        price: "",
                        description: "",
                        idd: this.idd,
                        commissionAmount: "",
                        commissionRate: ""
                    };
                    this.form.nurseStationItemPrices.push(obj);
                }
                this.open = true;
                this.title = "修改护理站护理项目";
            });
        },
        /** 提交按钮 */
        submitForm() {
            if (this.form.nurseStationItemPrices.length > 0) {
                this.form.nurseStationItemPrices.forEach(e => {
                    if (!e.commissionAmount || e.commissionAmount == "") {
                        e.commissionAmount = null;
                    } else {
                        e.commissionAmount = Number(e.commissionAmount)
                    }
                    if (!e.commissionRate || e.commissionRate == "") {
                        e.commissionRate = null;
                    } else {
                        e.commissionRate = Number(e.commissionRate)
                    }
                });
            }
            if (this.form.nurseStationItemConsumables.length > 0) {
                this.form.nurseStationItemConsumables.forEach(e => {
                    e.nurseStationConsumableId = e.id;
                    e.consumableCount = Number(e.consumableCount);
                });
            }
            this.form.nurseStationItem.nurseTypeId = this.form.nurseTypeId;
            if (!this.form.nurseStationItem.appointmentLimitCount) {
                this.form.nurseStationItem.appointmentLimitCount = null
            }
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.nurseStationItem.id != null) {
                        this.form.nurseStationItemPrices.forEach((e) => {
                            e.nurseStationItemId = this.form.nurseStationItem.id;
                        });
                        var obj = { pictureUrlList: [] };
                        if (this.imgone != this.form.nurseStationItem.itemPictureUrl) {
                            obj.pictureUrlList.push(this.imgone);
                        }
                        if (obj.pictureUrlList.length > 0) {
                            updatePicture(obj).then((res) => {});
                        }
                        this.imgsurl = { pictureUrlList: [] };
                        this.form.nurseStationItemPrices.forEach(e => {
                            e.price = Number(e.price)
                        })
                        updateNurseItem(this.form).then((response) => {
                            if (response.code == 200) {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                            }
                        });
                    } else {
                        this.form.nurseStationItemPrices.forEach(e => {
                            e.price = Number(e.price)
                        })
                        addNurseItem(this.form).then((response) => {
                            if (response.code == 200) {
                            this.$modal.msgSuccess("新增成功");
                            this.$forceUpdate();
                            this.open = false;
                            this.getList();
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            var that = this;
            this.$modal
                .confirm("是否确认删除此护理站护理项目？")
                .then(function() {
                    delNurseItem(ids).then(res => {
                        var obj = { pictureUrlList: [] };
                        obj.pictureUrlList.push(row.itemPictureUrl);
                        updatePicture(obj).then((res) => {});
                        that.getList();
                        that.$modal.msgSuccess("删除成功");
                    })
                })
                .catch(() => {});
        },
        /** 导入按钮操作 */
        handleExport() {
            this.upload.title = "护理站护理项目导入";
            this.upload.open = true;
        },
    },
};