<template>
  <Container>
    <Table v-if="merchantId" ref="table" :queryApi="list" :labelWidth="'70px'">
      <template #search>
          <CategoryCascader label="服务类型" prop="cateId"/>
          <Input label="服务主题" prop="name" :maxlength="30" />
          <Input label="服务编号" prop="goodsIndex"/>
          <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="goodsServerList"><template #default="{row}">{{(row.goodsServerList || []).length}}</template></Column>
          <DateColumn label="创建时间" prop="createTime" />
          <DictColumn label="状态" prop="isSale" dictType="goods_status"/>
          <Column label="操作" :min-width="300">
            <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="() => onShelf(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>
      </template>
    </Table>
    <el-alert v-else title="当前用户不存在商品信息" type="error" :closable="false" center/>

    <el-dialog 
       title="创建服务"
       :visible.sync="goodsOpen"
        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"
            />
            <p class="t"> 
            <cell class="idea">
              {{ideaContent}}
              <br>
              {{imagesContent}}
            </cell>
            </p>
            <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"/>
            <DictSelect ref="goodsUnit" label="报价单位" prop="goodsUnit" dictType="goods_unit" :placeholder="goodsUnitPlaceholder" emptyLabel="请选择" required/>
            <Input class="other-unit" v-if="isOtherUnit" label="其他单位" placeholder="其他单位，如: 平方米" prop="otherUnit" :maxlength="6" required/>
            <span v-if="isOtherUnit" class="suffix">选择价格后面的单位，例如: <u>平方米</u></span>
            <InputNumber :disabled="isHourUnit" label="大概服务时长（小时）" :max="999.9" :precision="1" prop="singleTime" required/>
            <Cell>{{remarkContent}}</Cell>
            <ServerUserSelector label="选择服务人员" prop="serverUserList" :priceLabel="priceLabel" :disabled="isDetail" required/>
        </Form>
        <div style="width: 100%; text-align:center">
            <el-button @click="goodsOpen=false">返回</el-button>
            <el-button type="primary" v-show="!isDetail" @click="handleSave" :loading="saving">保存</el-button>
        </div>
    </div>
    </el-dialog>

  </Container>
</template>

<script>
import CategoryCascader from './components/CategoryCascader.vue'
import { mapGetters } from 'vuex'
import {list, remove, onShelf, offShelf} from '@/api/merchant/merchantService'
import{detail} from'@/api/merchant/merchant'
import ServerUserSelector from './components/ServerUserSelector.vue'
import {save,goods} from '@/api/merchant/merchantService'


export default {
  name: "MerchantService",
  components: {CategoryCascader,ServerUserSelector},
  data(){
    return {
      goods:"",
      goodsOpen:false,
      isShowVideo:true,
      isShowImages:true,
      text:"",
      form: {
        serverUserList: [],
        images: "",
        video:"",
        serviceDesc: "",
        priceDesc: "", 
                
        },
      saving: false,
      key:new Date().getTime()
    }
  },
  props: {
        goodsId: {
            type: String,
        },
        isDetail: {
            type: Boolean,
            default: false,
        },
        flag:{
            type:Boolean,
            default:false,
        }
    },
  computed: {
    ...mapGetters(['merchantId']),
        ideaContent(){
            return '视频：建议比例16：9，大小50M内'
        },
        imagesContent(){
            return '图片：建议尺寸750*600px，最多9张'
        },
        coinRemark(){
            return '设置顾客下单，服务完成后点评此服务奖励的优金豆数量，请不要高于商品营业额的20%，100个优金豆相当于1元人民币。'
        },
        goodsUnitPlaceholder(){
            return '选择价格后面的单位，例如：200元 / 50平方米'
        },
        remarkContent(){
            return `注：请填写服务完成每个单位项目的大概时长，例如：此项目为擦玻璃 50元/50平方米，
                填写大概时长0.5小时，如果顾客下单数量x2，即100平方米，系统会自动计算大概时长1小时。
                此时长只作为判断一个服务人员在某个时间段内是否有服务中的订单，是否允许预约。`
        },
        isOtherUnit(){
            return this.form.goodsUnit === '999'
        },
        isHourUnit(){
            const isHour = this.form.goodsUnit === '1'
            if (isHour) {
                this.form.singleTime = 1
            }
            return isHour
        },
        priceLabel(){
            const {goodsUnit, otherUnit} = this.form
            if (!goodsUnit || goodsUnit.trim() === '' ||
                (this.isOtherUnit && (!otherUnit || otherUnit.trim() === ''))) {
                return '单价（ 元 / 待选择 ）'
            }
            return `单价（ 元 / ${this.isOtherUnit? otherUnit: this.$refs.goodsUnit?.selectedLabel || '待选择'} ）`
        }
  },

  created(){
        this.getDetail()
    },
    watch:{
        goodsId(){
            this.getDetail()
        }
    },
  methods: {
    list, onShelf, offShelf,
    async handleSave(){
      
            // 校验必填字段是否填写  
            try {
                await this.$refs.form.validate();
            } catch (error) {
                return
            }
            // 校验其他信息
            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 (const {goodsServerPrice} of this.form.serverUserList) {
                if (!goodsServerPrice) {
                    this.$message.warning('服务人员单价不能为空，且必须大于0')
                    return
                }
            }

            this.saving = true
            try{
                await save(this.form)
                this.$message.success('保存成功')
                this.goodsOpen=false
                this.form={}
                this.$refs.table.getList()
            } finally {
                this.saving = false
            }
        },
        async getDetail(){
            if (!this.goodsId) {
              debugger
                return
            }
            const {data} = await goods(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
        },
    handleAdd(){
      this.isShowVideo=true;
      this.isShowImages=true;
      // //获得当前商家数据
      // if (!this.merchantId) {
      //           return
      //       }
      this.key = new Date().getTime();
      this.form= {
                serverUserList: [],
                images: "",
                video:"",
                serviceDesc: "",
                priceDesc: "", 
                
            },
            
            this.goodsOpen=true
            this.isDetail=false
       
      //判断商家是否有地址信息
        //  detail(this.merchantId).then((res) => {
        //     if (res.code === 200) {
        //         if(res.data.address.latitude>0 && res.data.address.longitude>0){
        //           // this.$router.push('/merchant/service/create')
        //           //  this.goodsOpen=true
                  
        //         }else{
        //           // this.$message.success('请先配置店铺地址')
        //           this.updeteMerchant();
        //         }
        //       }else{
        //         this.updeteMerchant();
        //       }
        //   });

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

                }catch(error){}
        },
    handleModify(row){
      // this.$router.push('/merchant/service/modify?goodsId='+goodsId)
      const goodsId = row.goodsId
      this.isShowVideo=true;
      this.isShowImages=true;
      goods(goodsId).then((response) => {
        this.form=response.data
        this.getDetail(goodsId)
        this.key = new Date().getTime();
        this.goodsOpen=true
        this.isDetail=false
      })
    },
    handleDetail(row){
      // this.$router.push('/merchant/service/detail?goodsId='+goodsId)
      const goodsId = row.goodsId
      this.isShowVideo=true;
      this.isShowImages=true;
      goods(goodsId).then((response) => {
        this.form=response.data
        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.getDetail(goodsId)
        this.goodsOpen=true
      })
      this.key = new Date().getTime();
      this.isDetail=true
    },
    async remove({name, goodsId}){
      await this.$modal.confirm('是否确认删除服务主题为"' + name + '"的数据项？')
      const {code} = await remove(goodsId)
      if (code === 200) {
        this.$message.success('删除成功')
        this.$refs.table.getList()
      }
    },


    async onShelf({name, goodsId}){
      await this.$modal.confirm('是否确认上架服务主题为【' + name + '】的数据项？')
      const {code} = await onShelf(goodsId)
      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()
      }
    }
  }
}
</script>
<style>

.merchant-service-form.el-form--inline .el-form-item {
  width: calc(50% - 10px);
}
.merchant-service-form>.el-form-item>.el-form-item__content>.el-input,
.merchant-service-form>.el-form-item>.el-form-item__content>.el-input-number,
.merchant-service-form>.el-form-item>.el-form-item__content>.el-input-number>.el-input,
.merchant-service-form>.el-form-item>.el-form-item__content>.el-select>.el-input,
.merchant-service-form>.el-form-item>.el-form-item__content>.el-cascader>.el-input {
  width: 300px;
}

.merchant-service-form.el-form--inline .coin{
    width: 500;
}

.suffix{
    font-size: 14px;
    color: #FF6600;
    line-height: 20px;
    padding-left: 20px;
}
.other-unit{
    width: 500px;
    display: inline-block;
}

.idea{
    color: #999999;
   
}
</style>
