<template>
    <div class="app-container" v-if="roles[0] ==='merchant'">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="80px"
        >
            <el-form-item label="发布日期">
                <el-date-picker
                    v-model="searchDate"
                    type="daterange"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    align="left"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    clearable
                    size="small"
                    style="width: 260px"
                    :default-time="['00:00:00', '23:59:59']"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="服务类型">
                <el-cascader
                    v-model="queryParams.categoryId"
                    :options="categoryList"
                    :props="optionProps"
                    size="small"
                    clearable
                ></el-cascader>
            </el-form-item>

            <el-form-item label="任务标题" prop="goodsName">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入服务主题"
                    maxlength="30"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item label="状态">
                <el-select
                    v-model="queryParams.status"
                    placeholder="请选择"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                >
                    <el-option label="全部" value=""></el-option>
                    <el-option label="已报价" value="1"></el-option>
                    <el-option label="未报价" value="0"></el-option>
                    <el-option label="被选中" value="2"></el-option>
                    <el-option label="被抢单" value="3"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-search"
                    @click="handleQuery"
                    plain
                    >搜索
                </el-button>
                <el-button
                    icon="el-icon-refresh"
                    size="small"
                    @click="resetQuery"
                    >重置
                </el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="pageList" border stripe>
            <el-table-column
                label="任务ID"
                align="center"
                prop="publishId"
                width="120"
            />
            <el-table-column
                label="任务标题"
                align="center"
                prop="name"
                width="250"
                show-overflow-tooltip
            />
            <el-table-column
                label="任务类型"
                align="center"
                prop="categoryName"
                width="200"
            >
                <template slot-scope="scope">
                    <span>{{ parseCategory(scope.row) }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="地址"
                align="center"
                prop="publishAddress"
                width="260"
            >
                <template slot-scope="scope">
                    <span>{{ parseAddress(scope.row.publishAddress) }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="留言人数"
                align="center"
                prop="quoteCount"
                width="100"
            />

            <el-table-column
                label="发布时间"
                align="center"
                prop="createTime"
                width="160"
            >
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="businessState">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.status == 1" type="success"
                        >已报价</el-tag
                    >
                    <el-tag v-if="scope.row.status == 0" type="info"
                        >未报价</el-tag
                    >
                    <el-tag v-if="scope.row.status == 2" type="success"
                        >被选中</el-tag
                    >
                    <el-tag v-if="scope.row.status == 3" type="info"
                        >被抢单</el-tag
                    >
                    <el-tag v-if="scope.row.status == 4" type="info"
                        >已下架</el-tag
                    >
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                width="220"
                fixed="right"
            >
                <template slot-scope="scope">
                    <el-button
                        type="text"
                        icon="el-icon-view"
                        @click="getPublishDetail(scope.row.publishId)"
                        v-hasPermi="['system:publish:query']"
                        >查看详情
                    </el-button>
                    <el-button
                        v-if="scope.row.status === 0"
                        type="text"
                        icon="el-icon-upload2"
                        @click="quote(scope.row)"
                        v-hasPermi="['shop:audit:audit']"
                        >报价
                    </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"
                label-width="120px"
                style="height: 100px"
            >
                <el-input
                    type="textarea"
                    :rows="4"
                    v-model="form.closeReason"
                    placeholder="请输入下架的原因"
                />
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 报价对话框 -->
        <el-dialog
            title="我要报价"
            :visible.sync="quoteOpen"
            width="500px"
            append-to-body
        >
            <el-form
                ref="quoteForm"
                :model="quoteParams"
                label-width="120px"
                :rules="quoteRules"
            >
                <el-form-item label="报价描述">
                    <el-input
                        type="textarea"
                        :rows="4"
                        maxlength="500"
                        show-word-limit
                        placeholder="请输入内容"
                        v-model="quoteParams.quoteDesc"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="单价" prop="singlePrice">
                    <el-input-number
                        placeholder="请输入单价"
                        v-model="quoteParams.singlePrice"
                        :controls="false"
                        :min="0"
                        :max="99999999.99"
                        :precision="2"
                        @blur="countTotalPrice()"
                    >
                        <template slot="append">元</template>
                    </el-input-number>
                </el-form-item>
                <el-form-item label="单位" prop="quoteUnit">
                    <el-select
                        placeholder="请选择单位"
                        v-model="quoteParams.quoteUnit"
                        @change="justifyOther"
                        style="width: 100%"
                    >
                        <el-option
                        v-for="item in unitsOption"
                        :label="item.dictLabel"
                        :value="item.dictSort"
                        :key="item.dictSort"
                    ></el-option>
                    </el-select>
                    <el-input
                        v-if="otherUnitFlag"
                        v-model="quoteParams.otherUnit"
                        style="margin-top: 20px"
                        placeholder="其他单位:如“平方米”"
                    ></el-input>
                </el-form-item>
                <el-form-item label="单位时长" prop="singleTime">
                    <el-select
                        v-model="quoteParams.singleTime"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="(item, index) in timeList"
                            :label="item + '小时'"
                            :value="item"
                            :key="item"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数量" prop="quoteCounts">
                    <el-input-number
                        placeholder="请输入数量"
                        v-model="quoteParams.quoteCounts"
                        :controls="false"
                        :min="0"
                        :max="99999"
                        :precision="0"
                        @blur="countTotalPrice()"
                    >
                    </el-input-number>
                </el-form-item>
                <el-form-item label="服务人员" prop="serverUserId">
                    <el-select
                        placeholder="请选择服务人员"
                        v-model="quoteParams.serverUserId"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="(item, index) in serverUserOption"
                            :label="item.realName"
                            :value="item.serverId"
                            :key="item.serverId"
                        ></el-option>
                    </el-select>
                    <span style="color: red">注:如被选中则由此人来服务。</span>
                </el-form-item>
                <div style="float: right; margin-left: 0px">
                    总计：<span style="color: #ff0000">{{
                        (isNaN(quoteParams.quoteCounts) ? 0 : quoteParams.quoteCounts) * (isNaN(quoteParams.singlePrice) ? 0 : quoteParams.singlePrice)
                    }}</span
                    >元 /
                    <span style="color: #ff0000">{{
                        (isNaN(quoteParams.quoteCounts) ? 0 : quoteParams.quoteCounts) * (isNaN(quoteParams.singleTime) ? 0 : quoteParams.singleTime)
                    }}</span
                    >小时
                </div>
                <el-form-item>
                    <el-button type="primary" @click="saveQuote()">保存</el-button>
                    <el-button @click="qteCancel()">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
    <el-alert v-else title="当前用户不存在任务列表信息" type="error" :closable="false" center/>
</template>

<script>
import { listPublish } from "@/api/publish/publish";
import { categoryTree } from "@/api/basic/category";
import { listDownSelectUser } from "@/api/system/ServiceUserService";
import { getInfo } from "@/api/login";
import { listCode } from "@/api/system/dict/code";
import { getDicts } from "@/api/system/dict/data";
import { addQuote, updateQuote, delQuote } from "@/api/publish/quote";
import { detail } from "@/api/merchant/merchant";
import { mapGetters } from "vuex";

export default {
    name: "adminMerchant",
    data() {
        return {
             // 角色
            userRole: "",
            otherUnitFlag: false,
            showSearch: true,
            loading: true,
            total: 0,
            pageList: [],
            merchantId: "",
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: "",
                status: "",
                categoryId: [],
                merchantId: "",
                beginTime: "",
                endTime: "",
                merchantLatitude: null,
                merchantLongitude: null,
            },
            form: {},
            // 弹出层标题
            title: "",
            open: false,
            searchDate: "",
            categoryList: [],
            optionProps: {
                value: "categoryId",
                label: "categoryName",
                children: "childrenCategory",
            },
            timeList: [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6],
            //报价参数
            quoteParams: {
                quoteDesc: null,
                quoteUnit: null,
                otherUnit: null,
                serverUserId: null,
                merchantId: null,
                quoteCounts: undefined,
                singlePrice: undefined,
                singleTime: null,
                totalPrice: 0,
                totalTime: null,
                status: 0,
                publishId: null,
                quoteId: null,
            },
            quoteOpen: false,
            //报价服务人员选项
            serverUserOption: [],
            //单价选项
            unitsOption: [],
            //报价 表单校验
            quoteRules: {
                singlePrice: [
                    {
                        required: true,
                        message: "单价不能为空",
                        trigger: "blur",
                    },
                ],
                otherUnit: [
                    {
                        required: true,
                        message: "单位不能为空",
                        trigger: "blur",
                    },
                ],
                quoteCounts: [
                    {
                        required: true,
                        message: "数量不能为空",
                        trigger: "blur",
                    },
                ],
                quoteUnit: [
                    {
                        required: true,
                        message: "单位不能为空",
                        trigger: "blur",
                    },
                ],
                serverUserId: [
                    {
                        required: true,
                        message: "服务人员不能为空",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    created() {
        this.getList();
        this.categoryTree();
    },
    mounted() {
        this.listUser();
        this.listUnit();
    },
    computed: {
        ...mapGetters(["roles"]),
    },
    methods: {
        // 报价参数重置
        resetQuoteParams() {
            this.quoteParams = {
                quoteDesc: null,
                quoteUnit: null,
                otherUnit: null,
                serverUserId: null,
                merchantId: null,
                quoteCounts: undefined,
                singlePrice: undefined,
                singleTime: 0.5,
                totalPrice: 0,
                totalTime: 0,
                status: 0,
                publishId: null,
                quoteId: null,
            };
            // 清空表单
            if (this.$refs.quoteForm) {
                this.$refs.quoteForm.clearValidate()
            }
        },
        //报价对话框计算总价
        countTotalPrice() {
            if (
                this.quoteParams.singlePrice &&
                this.quoteParams.singlePrice < 0.01
            ) {
                return this.$modal.msgError("单价不能小于0.01");
            }
            if (
                this.quoteParams.singlePrice
                &&
                this.quoteParams.quoteCounts
            ) {
                console.log(1);
                this.queryParams.totalPrice =
                    this.quoteParams.singlePrice * this.quoteParams.quoteCounts;
            }
        },
        justifyOther(value) {
            console.log(value);
            if (value == 999) {
                this.otherUnitFlag = true;
            } else {
                this.otherUnitFlag = false;
            }
        },
        // 保存报价
        saveQuote() {
            this.quoteParams.merchantId = this.merchantId;
            this.quoteParams.totalPrice =
                this.quoteParams.singlePrice * this.quoteParams.quoteCounts;
            this.quoteParams.totalTime =
                this.quoteParams.singleTime * this.quoteParams.quoteCounts;
            // 校验参数
            if (!this.quoteParams.singlePrice) {
                return this.$modal.msgError("请输入单价");
            }
            if (!this.quoteParams.quoteUnit) {
                return this.$modal.msgError("请选择单位");
            }
            if (!this.quoteParams.quoteCounts) {
                return this.$modal.msgError("请输入数量");
            }
            if (!this.quoteParams.serverUserId) {
                return this.$modal.msgError("请选择服务人员");
            }
            if (this.quoteParams.quoteDesc && this.quoteParams.quoteDesc.length > 500) {
                return this.$modal.msgError("报价描述字数不得超过500")
            }
            if (this.quoteParams.otherUnit && this.quoteParams.otherUnit.length > 10) {
                return this.$modal.msgError("其他单位长度不得超过10")
            }

            addQuote(this.quoteParams).then((res) => {
                if (res.code === 200) {
                    // 关闭报价框
                    this.quoteOpen = false;
                    // 刷新列表
                    this.getList();
                }
            });
        },

        // 取消报价
        qteCancel() {
            // 关闭报价框
            this.quoteOpen = false;
            // 重置报价参数
            this.resetQuoteParams();
        },

        // 查询服务人员下拉选
        listUser() {
            getInfo().then((r) => {
                this.userRole = r.roles[0];
                if (r.roles[0] == "merchant") {
                    if (r.merchant.merchantId != null) {
                        this.merchantId = r.merchant.merchantId;
                        if (this.merchantId != null) {
                            let param = {
                                merchantId: this.merchantId.toString(),
                            };
                            listDownSelectUser(param).then((res) => {
                                this.serverUserOption = res.rows;
                            });
                        }
                    }
                }
            });
        },

        //加载报价单位
        listUnit() {
            // let param = {
            //     codeValue: "报价单位",
            // };
            // listCode(param).then((res) => {
            //     this.unitsOption = res.rows;
            // });

            //查询报检单位集合
            let param = "goods_unit";
             getDicts(param).then((res) => {
                 if(res.code==200){
                    this.unitsOption = res.data;
                 }
            });
        },
        quote(row) {
            this.resetQuoteParams();

            this.quoteParams.publishId = row.publishId;

            for (let i in this.serverUserOption) {
                if (row.serverUserId == this.serverUserOption[i].serverId) {
                    this.quoteParams.serverUserId =
                        this.serverUserOption[i].serverId;
                }
            }
            for (let j in this.unitsOption) {
                if (
                    row.quoteUnit == this.unitsOption[j].dictSort &&
                    row.quoteUnit !== 999
                ) {
                    this.quoteParams.quoteUnit = this.unitsOption[j].dictSort;
                } else if (
                    this.unitsOption[j].dictSort == 999 &&
                    row.quoteUnit == 999
                ) {
                    this.quoteParams.quoteUnit = this.unitsOption[j].dictSort;
                    this.quoteParams.otherUnit = row.otherUnit;
                    this.otherUnitFlag = true;
                }
            }
            this.quoteOpen = true;
        },
        categoryTree() {
            categoryTree()
                .then((res) => {
                    if (res.code == 200) {
                        this.categoryList = res.data;
                    } else {
                        this.$message.error("获取分类列表失败");
                    }
                    console.log(res);
                })
                .catch((err) => {
                    this.$message.error("获取分类列表失败");
                    console.log(err);
                });
        },
        /** 查询待审核列表 */
        getList() {
            this.loading = true;
            if (this.searchDate == null) {
                this.searchDate = "";
            }
            const [searchBegin, searchEnd] = this.searchDate;
            let sBegin = searchBegin;
            let sEnd = searchEnd;
            if (typeof searchBegin == "undefined") {
                sBegin = "";
            }
            if (typeof searchEnd == "undefined") {
                sEnd = "";
            }
            this.queryParams.beginTime = sBegin;
            this.queryParams.endTime = sEnd;
            // 级联选择器绑定的参数queryParams.categoryId是一个数组，需要将最后一个层级分类的id 重新赋值给查询参数categoryId
            if (this.queryParams.categoryId && this.queryParams.categoryId.length > 1) {
                this.queryParams.categoryId =
                    this.queryParams.categoryId[
                        this.queryParams.categoryId.length - 1
                    ];
            }
            getInfo().then((r) => {
                if (r.roles[0] == "merchant") {
                    if (r.merchant.merchantId != null) {
                        this.queryParams.merchantId = r.merchant.merchantId;
                        detail(this.queryParams.merchantId).then((res) => {
                            //获取商家经纬度
                            this.queryParams.merchantLatitude =
                                res.data.latitude;
                            this.queryParams.merchantLongitude =
                                res.data.longitude;
                            listPublish(this.queryParams)
                                .then((response) => {
                                    console.log(response);
                                    this.pageList = response.rows;
                                    this.total = parseInt(response.total);
                                })
                                .catch((err) => {
                                    console.log(err);
                                })
                                .finally(() => {
                                    this.loading = false;
                                });
                        });
                    }
                } else {
                    listPublish(this.queryParams)
                        .then((response) => {
                            console.log(response);
                            this.pageList = response.rows;
                            this.total = parseInt(response.total);
                        })
                        .catch((err) => {
                            console.log(err);
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                }
            });
        },
        // 表单重置
        reset() {
            this.form = {
                merchantId: null,
                examineReason: null,
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.searchDate = [];
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                name: "",
                status: "",
                categoryId: [],
                merchantId: "",
                beginTime: "",
                endTime: "",
            };
            this.handleQuery();
        },

        // 查询需求详情信息
        getPublishDetail(publishId) {
            this.$router.push({
                path: "/publish/publishDetails",
                query: {
                    publishId: publishId,
                },
            });
        },

        parseAddress(address) {
            if (address == null) {
                return "--";
            }
            return address.address + "-" + address.detailed;
        },

        parseCategory(row) {
            if (row.parentCategoryName == null) {
                return row.categoryName;
            }
            return row.parentCategoryName + " - " + row.categoryName;
        },

        /** 提交按钮 */
        submitForm() {
            if (this.form.closeReason == null) {
                this.$message.error("下架原因不可为空");
                return;
            }
            if (this.form.merchantId != null) {
                takeOff(this.form)
                    .then((res) => {
                        if (res.code == 200) {
                            this.$message.success("下架成功");
                        } else {
                            this.$message.error(res.msg);
                        }
                        this.open = false;
                        this.getList();
                        console.log(res);
                    })
                    .catch((err) => {
                        console.log(err);
                        this.$message.error("操作失败");
                    });
            }
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
    },
};
</script>

<style scoped="scoped"></style>
