<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item prop="appUserName" label-width="90px">
                <el-input v-model="queryParams.appUserName" placeholder="请输入派送员姓名" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item prop="phoneNumber" label-width="100px">
                <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" clearable maxlength="11" @keyup.enter.native="handleQuery" />
            </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-plus" @click="handleAdd" v-hasPermi="['app:delivery:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate" v-hasPermi="['app:delivery:edit']">修改</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <Page uri="/mapi/app/delivery/page" :request-params="queryParams" ref="pagination">
            <el-table-column label="姓名" align="center" prop="realName" width="150" />
            <el-table-column label="手机号" align="center" prop="phoneNumber" width="150" />
            <el-table-column label="简介" align="center" prop="description" width="220" show-overflow-tooltip />
            <el-table-column label="等级" align="center" prop="level" />
            <el-table-column label="绑定门店数量" align="center">
                <template slot-scope="scope">
                    <span> {{ scope.row.relationStoreNum == null ? '0' : scope.row.relationStoreNum }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['app:delivery:edit']">修改</el-button>
                    <el-button type="text" icon="el-icon-delete" @click="recordDetail(scope.row)" v-hasPermi="['app:delivery:edit']">接单记录</el-button>
                </template>
            </el-table-column>
        </Page>
        <!-- 添加或修改配送员对话框 -->
        <el-dialog :title="title" :visible.sync="open" size="50%" append-to-body>
            <el-row :gutter="10" style="margin-right: 20px; margin-left: 20px; width: 95%">
                <el-card class="box-card custom-card" style="height: 800px">
                    <div slot="header" class="clearfix">
                        <span>选择客户</span>
                    </div>
                    <el-form :model="phoneNumber" size="small" :inline="true" label-width="68px">
                        <el-col :span="24" v-if="isUpdate">
                            <el-form-item label="手机号" prop="phoneNumber">
                                <el-input label-width="110px" v-model="phoneNumber" placeholder="请输入手机号" clearable maxlength="11" @change="searchUser" />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="searchUser">查询</el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="appUserInfo">
                            <el-descriptions :column="2" style="margin-top: 20px">
                                <el-descriptions-item label="用户名">{{ appUserInfo.realName }}</el-descriptions-item>
                                <el-descriptions-item label="手机号">{{ appUserInfo.phoneNumber }}</el-descriptions-item>
                                <el-descriptions-item label="等级">{{ appUserInfo.level }}</el-descriptions-item>
                                <el-descriptions-item label="积分">{{ appUserInfo.pointBalance }}</el-descriptions-item>
                            </el-descriptions>
                        </el-col>
                        <el-col :span="24" v-if="appUserInfo">
                            <el-form-item label="绑定门店" label-width="80px" style="margin-top: 20px" required>
                                <el-transfer filterable v-model="orgValue" :data="orgData" :titles="['未绑定的门店', '已绑定的门店']"></el-transfer>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="appUserInfo">
                            <el-form-item label="简介">
                                <el-input v-model="description" type="textarea" placeholder="请输入配送员简介" maxlength="500" :rows="5" style="width: 260px" show-word-limit />
                            </el-form-item>
                        </el-col>
                    </el-form>
                </el-card>
            </el-row>
            <el-row> </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 v-loading="loading" :title="recordDetailTitle" :visible.sync="openDetail" size="80%" append-to-body>
            <div class="head-column1" style="margin-top: 5px">
                <el-table fit highlight-current-row border stripe :data="recordDetailList">
                    <el-table-column label="订单编号" align="center" prop="orderNo" width="200" />
                    <el-table-column label="门店名称" align="center" prop="storeName" width="150" />
                    <el-table-column label="派送员姓名" align="center" prop="realName" width="100" />
                    <el-table-column label="派件方式" align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.sendClothWay == '0'">到店</span>
                            <span v-if="scope.row.sendClothWay == '1'">上门</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="派件时间" align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.sendClothWay == '0'">{{ scope.row.sendToStoreTime }}</span>
                            <span v-if="scope.row.sendClothWay == '1'">{{ scope.row.sendToUserTime }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="取件时间" align="center" prop="pickUpTime" />
                    <el-table-column label="送达时间" align="center" prop="finishTime" />
                </el-table>
                <pagination v-show="recordTotal > 0" :total="recordTotal" :page.sync="queryDetailParams.pageNum" :limit.sync="queryDetailParams.pageSize" @pagination="recordDetail" />
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listDelivery, getDelivery, delDelivery, addDelivery, updateDelivery, updateDeliveryStatus, getDeliveryOrderRecordList } from '@/api/app/delivery'
import { findUserByPhoneNumber } from '@/api/app/user'
import { allOrg } from '@/api/system/store'

export default {
    name: 'Delivery',
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            phoneNumber: [],
            appUserId: null,
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            recordTotal: 0,
            // 配送员表格数据
            deliveryList: [],
            // 弹出层标题
            title: '',
            recordDetailTitle: '',
            // 是否显示弹出层
            open: false,
            openDetail: false,
            // 查询参数
            queryParams: {
                appUserName: null,
                phoneNumber: null
            },
            // 查询参数
            queryDetailParams: {
                pageNum: 1,
                pageSize: 10,
                appUserId: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {},
            appUserInfo: null,
            // 简介
            description: null,
            isUpdate: true,
            orgData: [],
            orgValue: [],
            recordDetailList: []
        }
    },
    created() {
        allOrg().then((res) => {
            this.orgData = []
            res.data.forEach((org) => {
                if (org.sourceType == '02') {
                    this.orgData.push({
                        key: org.sourceType + ',' + org.id,
                        label: org.name
                    })
                }
            })
        })
        this.getList()
    },
    methods: {
        //搜索用户
        searchUser() {
            findUserByPhoneNumber({ phoneNumber: this.phoneNumber }).then((res) => {
                this.appUserInfo = res.data
            })
        },
        /** 查询配送员列表 */
        getList() {
            this.$nextTick(() => {
                this.$refs.pagination.handleSearch(true)
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.appUserInfo = null
            this.description = null
            this.phoneNumber = null
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.phoneNumber = selection.map((item) => item.phoneNumber)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.isUpdate = true
            this.appUserInfo = null
            this.description = null
            this.phoneNumber = null
            this.open = true
            this.title = '添加配送员'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.orgValue = []
            this.appUserInfo = null
            this.description = null
            const phoneNumber = row.phoneNumber || this.phoneNumber[0]
            findUserByPhoneNumber({ phoneNumber: phoneNumber }).then((res) => {
                this.appUserInfo = res.data
            })
            const id = row.id || this.ids
            getDelivery(id).then((response) => {
                this.form = response.data
                if (this.form.relationList != null && this.form.relationList.length > 0) {
                    this.form.relationList.forEach((vo) => {
                        this.orgValue.push(vo.sourceType + ',' + vo.orgId)
                    })
                }
                this.description = response.data.description
                this.isUpdate = false
                this.open = true
                this.title = '修改配送员'
            })
        },
        /** 提交按钮 */
        submitForm() {
            if (this.orgValue.length <= 0) {
                this.$message.error('请选择关联门店')
                return
            }
            const relationList = []
            this.orgValue.forEach((vo) => {
                relationList.push({
                    sourceType: vo.split(',')[0],
                    orgId: vo.split(',')[1]
                })
            })
            if (this.appUserInfo == null) {
                this.$message.error('请选择配送员')
                return
            }
            this.form.relationList = relationList
            if (this.form.id != null) {
                this.form.description = this.description
                updateDelivery(this.form).then((response) => {
                    this.$modal.msgSuccess('修改成功')
                    this.open = false
                    this.getList()
                    this.form = {}
                })
            } else {
                this.form.appUserId = this.appUserInfo.id
                this.form.description = this.description
                addDelivery(this.form).then((response) => {
                    this.$modal.msgSuccess('新增成功')
                    this.open = false
                    this.getList()
                    this.form = {}
                })
            }
        },
        recordDetail(row) {
            if (row.appUserId != null && row.appUserId != '') {
                this.appUserId = row.appUserId
                this.queryDetailParams.appUserId = row.appUserId
            } else {
                this.queryDetailParams.appUserId = this.appUserId
            }
            console.log(this.appUserId)
            getDeliveryOrderRecordList(this.queryDetailParams).then((response) => {
                this.recordDetailList = response.rows
                this.recordTotal = response.total
                this.openDetail = true
                this.recordDetailTitle = '接单记录'
            })
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        checkCloseDetail(done) {
            this.$confirm('是否关闭接单记录明细？')
                .then(function () {
                    done()
                })
                .then(() => {
                    this.appUserId = null
                    this.queryDetailParams = {
                        pageNum: 1,
                        pageSize: 10,
                        appUserId: null
                    }
                })
                .catch(() => {})
        },
        handleStatusChange(row) {
            let text = row.status === '0' ? '启用' : '停用'
            this.$confirm('确认要' + text + ' ' + row.name + ' 吗？')
                .then(function () {
                    return updateDeliveryStatus(row.id, row.status)
                })
                .then(() => {
                    this.$modal.msgSuccess(text + '成功')
                })
                .catch(function () {
                    row.status = row.status === '0' ? '1' : '0'
                })
        }
    }
}
</script>
