<template>

    <Container>
        <Table
            v-if="merchantId"
            ref="table"
            :queryApi="listGroupGoods"
            :labelWidth="'70px'"
        >
            <template #search>
                <CategoryCascader label="服务类型" prop="cateId" />
                <Input label="服务主题" prop="name" :maxlength="30" >
                <keep-alive>
                    <router-view/>
                </keep-alive>
                <!-- <Input label="服务编号" prop="goodsIndex"/> -->
                </Input>
                <DictSelect
                    label="状态"
                    prop="isSale"
                    dictType="goods_status"
                />
            </template>


            <template #operations>
                <p style="color: #FF6600;line-height: 20px;white-space: nowrap;text-transform: none;">注：此类服务项目为，商家发布服务项目，顾客下单购买后，通过电话沟通预约上门服务时间</p>
                <el-button
                    @click="handleAdd"
                    size="mini"
                    type="primary"
                    icon="el-icon-plus"
                    >创建服务</el-button
                >
            </template>
            <template #default>
                <!-- <Column type="index" label="序号"/> -->
                <Column label="服务编号" prop="goodsIndex" />
                <Column label="服务主题" prop="name" />
                <Column label="服务类型" prop="categoryName" />
                <Column
                    label="规格"
                    prop="goodsSpecificationList"
                    :min-width="100"
                    ><template #default="{ row }"
                        ><div
                            style="color: blue"
                            @click="() => handleGoodsSpecification(row)"
                        >
                            {{ (row.goodsSpecificationList || []).length }}种
                        </div></template
                    ></Column
                >
                <Column label="有效期" prop="expirationDateValue" :min-width="100">
                    <template #default="scope" >
                        {{scope.row.expirationDateValue > 0 ? `${scope.row.expirationDateValue}天`: '不限制'}}
                    </template>
                </Column>
                <DateColumn label="创建时间" prop="createTime" />
                <DictColumn
                    label="状态"
                    prop="isSale"
                    dictType="goods_status"
                />
                <Column label="操作" :min-width="260">
                    <template #default="{ row }">
                        <el-button
                            type="text"
                            @click="() => handleDetail(row)"
                            icon="el-icon-view"
                            >查看</el-button
                        >
                        <el-button
                            type="text"
                            @click="() => handleModify(row)"
                            icon="el-icon-edit"
                            >编辑</el-button
                        >
                        <el-button
                            v-if="row.isSale === 0"
                            type="text"
                            @click="() => onShelfGroup(row)"
                            icon="el-icon-top"
                            >上架</el-button
                        >
                        <el-button
                            v-if="row.isSale === 1"
                            type="text"
                            @click="() => offShelf(row)"
                            icon="el-icon-bottom"
                            >下架</el-button
                        >
                        <el-button
                            type="text"
                            @click="() => remove(row)"
                            icon="el-icon-delete"
                            >删除</el-button
                        >
                    </template>
                </Column>

                <!-- 团购服务规格信息弹框 -->
                <el-dialog
                    :title="title"
                    :visible.sync="open"
                    append-to-body
                >
                <el-row :gutter="10">
                    <el-col v-for="item in goodsSpecifications" :key="item.id" :span="8" style="margin-bottom: 10px">
                        <el-card>
                            <p>
                                <span style="margin-right: 35px; font-size: 22px; font-weight: bold;">{{item.currentPrice}}元</span>
                                <s style="font-size: 16px;">{{item.scribingPrice}}元</s>
                            </p>
                            <p>
                                <span style="margin-right: 20px; font-size: 13px;">{{item.specificationDesc}}</span>
                                <span>{{item.times}}次</span>
                            </p>
                        </el-card>
                    </el-col>

                </el-row>
                </el-dialog>
            </template>
        </Table>
        <el-alert
            v-else
            title="当前用户不存在商品信息"
            type="error"
            :closable="false"
            center
        />
        <el-dialog
                    title="创建服务"
                    :visible.sync="serviceOpen"
                    width="1500px"
                    :close-on-click-modal="false"
                    :modal-append-to-body="false"
                    :key="key"
                    >
                    <div >
                        <Form
                            ref="form"
                            class="merchant-service-form"
                            v-model="form"
                            :inline="false"
                            :labelWidth="'200px'"
                            :disabled="isDetail"
                        >
                            <Input label="服务主题" prop="name" required :maxlength="30" />

                            <Input
                                label="服务编号"
                                prop="goodsIndex"
                                required
                                :maxlength="40"
                                v-if="isDetail"

                            />

                            <CategoryCascader label="服务类型" prop="cateId" required />
                            <Images
                                label="轮播图"
                                prop="images"
                                :limit="8"
                                :disabled="isDetail"
                                :CutFlag="true"
                                v-if="isShowImages"
                            />
                            <Videos
                                :label="text"
                                prop="video"
                                :limit="1"
                                :disabled="isDetail"
                                v-if="isShowVideo"
                            />
                            <cell class="lbt">
                                {{ideaContent}}
                                <br>
                                {{imagesContent}}
                            </cell>
                            <Editor
                                label="服务内容"
                                prop="serviceDesc"
                                required
                                :disabled="isDetail"
                            />
                            <Editor
                                label="费用说明"
                                prop="priceDesc"
                                required
                                :disabled="isDetail"
                            />
                            <InputNumber
                                class="coin"
                                label="优金豆（个）"
                                prop="coin"
                                :max="99999"
                                required
                                :suffix="coinRemark"
                            />

                            <el-form-item label="规格" required="true">

                                <el-row
                                    v-for="(item, index) in form.goodsSpecificationList"
                                    :key="item.goodsSpecificationId"
                                >

                                    <label class="goods-specification-label" style="font-weight:normal;margin-right:5px;">描述</label>
                                    <el-input
                                        class="goods-specification-input"
                                        v-model="item.specificationDesc"
                                        size="small"
                                        style="width: 80px; margin-right:20px;"
                                        maxlength="50"
                                    />

                                    <label class="goods-specification-label" style="font-weight:normal;margin-right:5px;">次数</label>
                                    <el-input-number
                                        class="goods-specification-input"
                                        v-model="item.times"
                                        size="small"
                                        style="width: 120px;margin-right:20px;"
                                        maxlength="7"
                                        :min="1"
                                        :max="999"
                                    />

                                    <label class="goods-specification-label" style="font-weight:normal;margin-right:5px;">现价</label>
                                    <el-input
                                        class="goods-specification-input2"
                                        v-model="item.currentPrice"
                                        size="small"
                                        style="width: 100px;"
                                        maxlength="7"
                                        min="0.01"
                                        oninput="value=value.replace(/[^0-9.]/g,'') "
                                    /><span class="goods-specification-span" style="margin-right:20px;">元</span>

                                    <label class="specification-label" style="font-weight:normal;margin-right:5px;" >划线价</label>
                                    <el-input
                                        class="goods-specification-input2"
                                        v-model="item.scribingPrice"
                                        size="small"
                                        style="width: 100px;"
                                        maxlength="7"
                                        :min="0.01"
                                        oninput="value=value.replace(/[^0-9.]/g,'')"
                                    /><span class="goods-specification-span">元</span>
                                    <el-button
                                        style="margin-left: 20px;"
                                        type="primary"
                                        size="mini"
                                        icon="el-icon-plus"
                                        @click="add"
                                        plain
                                        >增加</el-button
                                    >
                                    <el-button
                                        v-if="
                                            form.goodsSpecificationList.length > 1 &&
                                            index > 0
                                        "
                                        type="danger"
                                        size="mini"
                                        icon="el-icon-minus"
                                        @click="del(index)"
                                        plain
                                        >删除</el-button
                                    >
                                </el-row>
                            </el-form-item>

<div id="expiration-date-wrapper">
    <div style="width:63%;margin:0; float:left;">
                            <Radio
                                class="expiration-date"
                                label="有效期"
                                :data="radioList"
                                prop="expirationDate"
                                :required="true"
                            />
    </div>
                            <div v-if="form.expirationDate === '6'" class="expiration-date" style="width:32%;margin:0 0 0 -200px; float:left;" >
                                <InputNumber
                                class="expiration-date-value"
                                prop="expirationDateValue"
                                :max="99999"
                                :min="1"
                                :label-width="'0px'"
                                style="width:100px;"
                                required
                            />
                              <span class="expiration-date-value-span" style=" float: left; margin-top:-45px; margin-left:39%">天</span>
                            </div>


</div>
<div style="clear: both;" > </div>

                            <InputNumber
                                label="限购数量"
                                :max="999"
                                :precision="0"
                                prop="maxNum"
                                :suffix="remarkContent"
                            />
                        </Form>
                        <div style="width: 100%; text-align: center">
                            <el-button @click="serviceOpen = false">返回</el-button>
                            <el-button
                                type="primary"
                                v-show="!isDetail"
                                @click="handleSave"
                                :loading="saving"
                                >保存</el-button
                            >
                        </div>
                    </div>
        </el-dialog>
    </Container>


</template>


<script>
import {detail} from '@/api/merchant/merchant'
import CategoryCascader from "./components/CategoryCascader.vue";
import { mapGetters } from "vuex";
import {
    listGroupGoods,
    remove,
    onShelfGroup,
    offShelf,
} from "@/api/merchant/merchantService";
import {
    listByGoodsId
} from "@/api/merchant/goodsSpecification";
import ServerUserSelector from "./components/ServerUserSelector.vue"
import { saveGroupGoods, getGroupGoodsDetail } from "@/api/merchant/merchantService";
import Cell from '../../../components/element/form/items/Cell.vue';





export default {
    name: "MerchantService",
    components: { CategoryCascader, ServerUserSelector, Cell  },
    props: {
        goodsId: {
            type: String,
        },
        isDetail: {
            type: Boolean,
            default: false,
        },
        flag:{
            type:Boolean,
            default:false,
        }
    },
    data() {

        return {
            isShowVideo:true,
            key:new Date().getTime(),
            isShowImages:true,
            text:"",
            form: {
                expirationDate: "1",
                images: "",
                video:"",
                serviceDesc: "",
                priceDesc: "",
                // 规格
                goodsSpecificationList: [
                    {
                        specificationDesc: "",
                        times: 1,
                        currentPrice: "",
                        scribingPrice: "",
                        merchantId: "",
                    },
                ],
            },

            radioList: [
                { label: "不限制", value: "1" },
                { label: "30天", value: "2" },
                { label: "60天", value: "3" },
                { label: "90天", value: "4" },
                { label: "365天", value: "5" },
                { label: "自定义", value: "6" },
            ],
            saving: false,
            serviceOpen:false,
            open: false,
            // 弹出层标题
            title: "",
            // 服务规格列表
            goodsSpecifications:[]
        };
    },

    computed: {
        ...mapGetters(["merchantId"]),
        dayContent() {
            return `天`;
        },
        ...mapGetters(['merchantId']),
        ideaContent(){
            return '视频：建议比例16：9，大小50M内'
        },
        imagesContent(){
            return '图片：建议尺寸750*600px，最多9张'
        },
        coinRemark() {
            return "设置顾客下单，服务完成后点评此服务奖励的优金豆数量，请不要高于商品营业额的20%，100个优金豆相当于1元人民币。";
        },
        remarkContent() {
            return `注：不输入数字即视为不限购买份数。`;
        },
    },
    created() {
        this.getDetail();
    },
        watch: {
        goodsId() {
            this.getDetail();
        },
    },
    methods: {
        listGroupGoods,
        onShelfGroup,
        offShelf,

        // 创建服务
        handleAdd() {
            this.isShowVideo=true;
            this.isShowImages=true;
            this.form = {
                expirationDate: "1",
                images: "",
                video:"",
                serviceDesc: "",
                priceDesc: "",
                // 规格
                goodsSpecificationList: [
                    {
                        specificationDesc: "",
                        times: 1,
                        currentPrice: "",
                        scribingPrice: "",
                        merchantId: "",
                    },
                ],
            }
            console.log(this.form.images)
            this.key = new Date().getTime();
            this.serviceOpen=true
            this.isDetail=false
            // debugger
            // this.$store.state.tagsView.visitedViews.forEach(element => {
            //     if (this.$route.path === element.path) {
            //         element.query = this.queryParams
            //     }
            // });
             //获得当前商家数据
            // if (!this.merchantId) {
            //     return
            // }
            //  //判断商家是否有地址信息
            // detail(this.merchantId).then((res) => {
            //     if (res.code === 200) {
            //         if(res.data.address.latitude>0 && res.data.address.longitude>0){
            //             //  this.$router.push("/merchant/groupService/create");
            //              console.log("jinlaile")

            //         }else{
            //        this.updeteMerchant();
            //         }

            //     }else{
            //    this.updeteMerchant();
            //     }
            // });

        },
        async updeteMerchant(){
             try{
                await this.$modal.confirm( '检测到您未配置服务范围，请先设置服务范围，再发布服务。');
                    this.$router.push(
                        "/merchant/area"
                    );

                }catch(error){}
        },

        // 编辑服务
        handleModify(row) {
            this.isShowVideo=true;
            this.isShowImages=true;
            // this.$router.push(
            //     "/merchant/groupService/modify?goodsId=" + goodsId
            // );
             const goodsId = row.goodsId
            getGroupGoodsDetail(goodsId).then((response) => {
                this.form=response.data
                this.getDetail(goodsId)
                this.key = new Date().getTime();
                this.serviceOpen=true
                this.isDetail=false
            })
        },
        // 查看服务详情
        handleDetail(row) {
            this.isShowVideo=true;
            this.isShowImages=true;
            // this.$router.push(
            //     "/merchant/groupService/detail?goodsId=" + goodsId
            // );
            const goodsId = row.goodsId
            getGroupGoodsDetail(goodsId).then((response) => {
                this.form=response.data
                this.getDetail(goodsId)
                if(this.form.video==""||this.form.video==null){
                    this.isShowVideo = false
                }else{
                    this.isShowVideo = true
                }
                if(this.form.images==""||this.form.images==null){
                    this.isShowImages = false
                    this.text="轮播图"
                }else{
                    this.isShowImages = true
                }
                this.key = new Date().getTime();
                this.serviceOpen=true
                this.isDetail=true
            })
            // this.orderOpen=true;


        },

        // 删除服务
        async remove({ name, goodsId }) {
             try{
                await this.$modal.confirm(
                    '是否确认删除服务主题为"' + name + '"的数据项？'
                );
                const { code } = await remove(goodsId);
                if (code === 200) {
                    this.$message.success("删除成功");
                    this.$refs.table.getList();
                }
             }catch(error){}
        },
        // 上架团购服务
        async onShelfGroup({ name, goodsId }) {
            await this.$modal.confirm(
                "是否确认上架服务主题为【" + name + "】的数据项？"
            );
            let data = {
                goodsId,
            };
            const { code } = await onShelfGroup(data);
            if (code === 200) {
                this.$message.success("上架成功");
                this.$refs.table.getList();
            }
        },
        // 下架团购服务
        async offShelf({ name, goodsId }) {
            await this.$modal.confirm(
                "是否确认下架服务主题为【" + name + "】的数据项？"
            );
            const { code } = await offShelf(goodsId);
            if (code === 200) {
                this.$message.success("下架成功");
                this.$refs.table.getList();
            }
        },

        // 查看服务规格信息
        handleGoodsSpecification(row) {
            this.open = true;
            this.title = "规格";
            let param = {
                goodsId: row.goodsId,
            };
            listByGoodsId(param).then((res) => {
                this.goodsSpecifications = res.data;
            });
        },
                async handleSave() {
            // 校验必填字段是否填写
            try {
                await this.$refs.form.validate();
            } catch (error) {
                return
            }
            // 校验其他信息
            if (this.form.expirationDate && this.form.expirationDate === '1') {
                // 不限制
                this.form.expirationDateValue = "-99"
            } else if (this.form.expirationDate && this.form.expirationDate === '2') {
                // 30天
                this.form.expirationDateValue = 30
            } else if (this.form.expirationDate && this.form.expirationDate === '3') {
                // 60天
                this.form.expirationDateValue = 60
            } else if (this.form.expirationDate && this.form.expirationDate === '4') {
                // 90天
                this.form.expirationDateValue = 90
            }else if (this.form.expirationDate && this.form.expirationDate === '5') {
                // 365天
                this.form.expirationDateValue = 365
            }

            const name = this.form.name;
            if (name && name.length > 30) {
                return this.$modal.msgError("服务主题长度不得超过30");
            }
            const images = this.form.images;
            const video = this.form.video;
            if ((!images&&!video) || ((images && images.length === 0)&&(video && video.length === 0))) {
                return this.$modal.msgError("轮播图不能为空");
            }

            for (var i = 0; i < this.form.goodsSpecificationList.length; i++) {
                 if (!this.form.goodsSpecificationList[i].specificationDesc || this.form.goodsSpecificationList[i].specificationDesc.length > 50) {
                    this.$message.warning("规格描述不能为空，且长度不得超过50");
                    return;
                }
                if (!this.form.goodsSpecificationList[i].times) {
                    this.$message.warning("规格次数不能为空，且必须大于0");
                    return;
                }
                if (!this.form.goodsSpecificationList[i].currentPrice || this.form.goodsSpecificationList[i].currentPrice < 0.01) {
                    this.$message.warning("规格现价不能为空，且必须大于或等于0.01");
                    return;
                }
                if (this.form.goodsSpecificationList[i].currentPrice && this.form.goodsSpecificationList[i].currentPrice < 0.01) {
                    this.$message.warning("规格现价不为空时必须大于或等于0.01");
                    return;
                }
                  if (!this.form.goodsSpecificationList[i].scribingPrice || this.form.goodsSpecificationList[i].scribingPrice < 0.01) {
                    this.$message.warning("规格划线价格不能为空，且必须大于或等于0.01");
                    return;
                }
                if (this.form.goodsSpecificationList[i].scribingPrice && this.form.goodsSpecificationList[i].scribingPrice < 0.01) {
                    this.$message.warning("规格划线价格不为空时必须大于或等于0.01");
                    return;
                }
                if (this.form.maxNum && this.form.maxNum < 1) {
                    this.$message.warning("限购数量不为空时必须大于或等于1");
                    return;
                }
                if (!this.merchantId) {
                    this.$message.warning("商家id不能为空");
                    return;
                } else {
                    this.form.goodsSpecificationList[i].merchantId = this.merchantId;
                }
            }

            this.saving = true;
            try {
                await saveGroupGoods(this.form);
                this.$message.success("保存成功");

                this.serviceOpen=false;
                this.form={};
                this.$refs.table.getList();
            } finally {
                this.saving = false;
            }
        },
        async getDetail() {
            if (!this.goodsId) {
                return;
            }
            const { data } = await getGroupGoodsDetail(this.goodsId);

            if(this.flag){
                if(data.video==""||data.video==null){
                this.isShowVideo = false
                }else{
                    this.isShowVideo = true
                }
                if(data.images==""||data.images==null){
                    this.isShowImages = false
                    this.text="轮播图"
                }else{
                    this.isShowImages = true
                }
            }

            this.form = data;
        },

        // 新增规格
        add() {
            let field = {
                specificationDesc: "",
                times: 1,
                currentPrice: "",
                scribingPrice: "",
            };
            this.form.goodsSpecificationList.push(field);
        },
        // 移除规格
        del(index) {
            if (this.form.goodsSpecificationList.length == 1) {
                this.$modal.msgError("至少需要一个规格");
                return;
            }
            this.form.goodsSpecificationList.splice(index, 1);
        },
    },
};
</script>


<style scoped>
.expiration-date-value-span{
    display: flex;
}
#expiration-date-wrapper{

width:100%;
margin : 0;

}
</style>
