<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入衣服名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="洗衣方式" prop="washModeId">
                <el-select v-model="queryParams.washModeId" placeholder="请选择洗衣方式" @change="handleQuery" filterable clearable>
                    <el-option v-for="(item, index) in clothWashModes" :key="index_" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="区域" prop="storeAreaId">
                <el-select v-model="queryParams.storeAreaId" placeholder="请选择区域" clearable @change="handleQuery" filterable>
                    <el-option v-for="(item, index) in areaList" :key="index_" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @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-document-copy" @click="handleCopy">复制区域</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-upload2" @click="handleImport">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" @click="handleExport">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row> -->

        <el-table v-loading="loading" fit highlight-current-row border stripe :data="laundryList">
            <el-table-column label="衣服ID" align="center" prop="clothId" />
            <el-table-column label="衣服名称" align="center" prop="name" />
            <el-table-column label="洗衣方式名称" align="center" prop="washModeName" />
            <el-table-column label="价格" align="center" prop="price">
                <template slot-scope="scope">
                    {{ scope.row.price ? scope.row.price : '未设置价格' }}
                </template>
            </el-table-column>
            <el-table-column label="区域" align="center" prop="areaName" />

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">设置</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="设置价格" :visible.sync="laundryPriceType" width="30%" :before-close="handleClose">
            <form ref="laundrypriceForm">
                <el-input-number v-model="laundrypriceForm.price" :min="1" :max="99999" :step="1" style="width: 100%" />
            </form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="laundryPriceType = false">取 消</el-button>
                <el-button type="primary" @click="setunitPrice('laundrypriceForm')">提 交</el-button>
            </span>
        </el-dialog>

        <!-- 复制区域 -->
        <el-dialog title="区域复制" :visible.sync="open" size="30%" append-to-body>
            <el-row :gutter="15">
                <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                    <el-col :span="24">
                        <el-form-item label="选择区域" prop="storeAreaIdFrom">
                            <el-select v-model="form.storeAreaIdFrom" placeholder="请选择区域" clearable filterable>
                                <el-option v-for="(item, index) in areaList" :key="index_" :label="item.name" :value="item.id" :disabled="item.id == form.storeAreaIdTo" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="复制区域" prop="storeAreaIdTo">
                            <el-select v-model="form.storeAreaIdTo" placeholder="请选择复制区域" clearable filterable>
                                <el-option v-for="(item, index) in areaList" :key="index_" :label="item.name" :value="item.id" :disabled="item.id == form.storeAreaIdFrom" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="价格倍数" prop="multiple">
                            <el-input-number v-model="form.multiple" :min="0.01" :max="100" :step="0.01" style="width: 100%" />
                            <div class="remark">价格倍数是以选择区域为底数乘以当前选择的价格倍数,最终得到复制区域的价格体系</div>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" style="margin-left: 5%">提交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="40%" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?storeAreaId=' + upload.storeAreaId" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listStoreArea } from '@/api/system/storeArea'
import { getClothPriceListByWashMode, setPriceByWashMode, setPriceByWashModeCopyArea, getWashMode } from '@/api/cloth/unitPrice'
import { getToken } from '@/utils/auth'

export default {
    name: 'laundryPrice',
    dicts: ['sys_normal_disable'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            clothType: null,
            // 单价表格数据
            laundryList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                storeAreaIdFrom: [{ required: true, message: '请选择区域', trigger: 'change' }],
                storeAreaIdTo: [{ required: true, message: '请选择复制区域', trigger: 'change' }],
                multiple: [{ required: true, message: '清填写价格倍数', trigger: 'blur' }]
            },
            areaList: [],
            laundryPriceType: false,
            laundrypriceForm: {},

            clothWashModes: [],

            // 导入参数
            upload: {
                // 是否显示弹出层（单价导入）
                open: false,
                // 弹出层标题（单价导入）
                title: '',
                // 是否禁用上传
                isUploading: false,
                //区域id
                storeAreaId: '',
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/mapi/cloth/price/importData'
            }
        }
    },
    created() {
        this.clothType = this.getUrlParam('clothType')
    },
    async mounted() {
        this.getAreaList()
        await this.getwashList()
        this.getList()
    },
    methods: {
        /** 查询衣服品牌列表 */
        getList() {
            this.loading = true
            getClothPriceListByWashMode(this.queryParams).then((response) => {
                console.log(response)
                this.laundryList = response.data.records
                this.total = response.data.total
                this.loading = false
            })
        },
        getAreaList() {
            listStoreArea({ pageSize: 10000, pageNum: 1, status: '0' }).then((res) => {
                this.areaList = res.rows
            })
        },
        // 表单重置
        reset() {
            this.form = {
                storeAreaIdFrom: null,
                storeAreaIdTo: null,
                multiple: null
            }
            this.resetForm('form')
        },
        // 取消按钮
        cancel() {
            this.reset()
            this.open = false
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 区域复制按钮操作 */
        handleCopy() {
            this.open = true
        },
        /** 设置按钮操作 */
        handleUpdate(row) {
            this.laundrypriceForm = Object.assign({}, row)
            this.laundryPriceType = true
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    setPriceByWashModeCopyArea(this.form).then((response) => {
                        this.$modal.msgSuccess('复制成功')
                        this.open = false
                        this.getList()
                    })
                }
            })
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },

        setunitPrice() {
            if (!this.laundrypriceForm.price) {
                this.$modal.msgError('请输入价格')
                return
            }
            setPriceByWashMode(this.laundrypriceForm).then((response) => {
                this.$modal.msgSuccess('设置成功')
                this.laundryPriceType = false
                this.getList()
            })
        },

        handleClose(done) {
            this.$confirm('是否关闭设置表单？')
                .then((_) => {
                    done()
                })
                .catch((_) => {})
        },

        getwashList() {
            getWashMode().then((res) => {
                this.clothWashModes = res.data
                this.queryParams.washModeId = this.clothWashModes[0].washModeId
            })
        },

        /** 导出按钮操作 */
        handleExport() {
            if (!this.queryParams.storeAreaId) {
                this.$modal.msgError('请选择区域')
                return
            }
            let primary = {
                storeAreaId: this.queryParams.storeAreaId
            }
            const up_name = this.areaList.find((item) => item.id === this.queryParams.storeAreaId)?.name
            this.downloadJson(
                '/mapi/cloth/price/exportData',
                {
                    ...primary
                },
                `${up_name}衣服单价列表.xlsx`
            )
        },
        /** 导入按钮操作 */
        handleImport() {
            if (!this.queryParams.storeAreaId) {
                this.$modal.msgError('请选择区域')
                return false
            }
            this.upload.storeAreaId = this.queryParams.storeAreaId
            const up_name = this.areaList.find((item) => item.id === this.queryParams.storeAreaId)?.name

            this.upload.title = `【${up_name}】 洗衣方式单价导入`
            this.upload.open = true
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download('/mapi/cloth/price/downloadTemplate', {}, `衣服单价导入模板.xlsx`)
        },

        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false
            this.upload.isUploading = false
            this.$refs.upload.clearFiles()
            var respMsg = response.code == '200' ? '' : '导入失败！'
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + respMsg + '<br/>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
            this.getList()
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit()
        }
    }
}
</script>
<style lang="scss" scoped>
.remark {
    margin-top: 10px;
    background-color: rgba(255, 228, 74, 0.1);
    border: 1px dashed #ffe44a;
    font-size: 14px;
    color: #e6a23c;
    width: 100%;
    padding: 20px;
    border-radius: 5px;
    line-height: 25px;
}
::v-deep .el-upload {
    width: 100%;
    .el-upload-dragger {
        width: 100%;
    }
}
</style>
