<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <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="个体户编号" prop="merchantIndex">
        <el-input
          v-model="queryParams.merchantIndex"
          placeholder="请输入个体户编号"
          maxlength="30"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入店铺名称"
          maxlength="30"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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-cascader
          v-model="queryParams.categoryId"
          :options="categoryList"
          :props="optionProps"
          size="small"
          clearable
          
        ></el-cascader>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="queryParams.isSale"
          placeholder="请选择"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        >
          <el-option label="全部" value></el-option>
          <el-option label="未上架" value="0"></el-option>
          <el-option label="已上架" value="1"></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="个体户编号" align="center" prop="merchantIndex" width="120" />
      <el-table-column
        label="手机号"
        align="center"
        prop="phonenumber"
        show-overflow-tooltip
      />
      <el-table-column
        label="服务编号"
        align="center"
        prop="goodsIndex"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="服务主题"
        align="center"
        prop="name"
        show-overflow-tooltip
      />
      <el-table-column
        label="服务类型"
        align="center"
        prop="categoryName"
        width="150"
      />
      <el-table-column
        label="服务人员数"
        align="center"
        prop="serverUserCount"
        width="150"
      />

      <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.isSale == '1'" type="success">
            已上架</el-tag
          >
          <el-tag v-if="scope.row.isSale == '0'" 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="queryDetails(scope.row)"
            v-hasPermi="['shop:audit:detail']"
          >查看详情
          </el-button>
          <el-button
            type="text"
            icon="el-icon-bottom"
            @click="takeOff(scope.row)"
            v-hasPermi="['shop:audit:audit']"
            v-if="scope.row.isSale == '1'"
          >下架
          </el-button>
          <el-button
            type="text"
            icon="el-icon-top"
            @click="takeOn(scope.row)"
            v-hasPermi="['shop:audit:audit']"
            v-if="scope.row.isSale == '0'"
          >上架
          </el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="deleteGoods(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="detailOpen"
            width="950px"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
        >
            <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}}</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="$router.go(-1)">返回</el-button>
            <el-button type="primary" v-show="!isDetail" @click="handleSave" :loading="saving">保存</el-button>
        </div>
    </div>
  </el-dialog>
  </div>
</template>

<script>
import { goodsTakeOn, goodsTakeOff, goodsList, deleteGoods} from "@/api/merchant/adminMerchant";
import { categoryTree } from "@/api/basic/category";
import CategoryCascader from '../../merchant/service/components/CategoryCascader.vue'
import ServerUserSelector from '../../merchant/service/components/ServerUserSelector.vue'
import {save, detail} from '@/api/merchant/merchantService'

export default {
  name: "adminMerchant",
  components: {CategoryCascader, ServerUserSelector},
  props: {
        goodsId: {
            type: String,
        },
        isDetail: {
            type: Boolean,
            default: false,
        },
        flag:{
            type:Boolean,
            default:false,
        }
    },
  data() {
    return {
      detailOpen:false,
       isShowVideo:true,
            isShowImages:true,
            text:"",
            form: {
                serverUserList: [],
                images: "",
                video:"",
                serviceDesc: "",
                priceDesc: "", 
                
            },
            saving: false,
      merchantType: 1,
      showSearch: true,
      loading: true,
      total: 0,
      pageList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pageCount: 10,
        phonenumber: "",
        name: "",
        isSale: '',
        categoryId: [],
        merchantId: "",
        merchantIndex: "",
        beginTime: "",
        endTime: "",
        merchantType: ""
      },
      form: {},
      // 弹出层标题
      title: "",
      open: false,
      searchDate: [],
      categoryList: [],
      optionProps: {
        value: "categoryId",
        label: "categoryName",
        children: "childrenCategory"
      }
    };
  },

  computed: {
        ideaContent(){
            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()
    if (this.$route.query.pageNum) {
            console.log(this.queryParams.pageNum)
            this.queryParams.pageNum = parseInt(this.$route.query.pageNum)
            console.log(this.queryParams.pageNum)
         }
    
        if (this.$route.query.merchantIndex) {
            this.queryParams.merchantIndex = this.$route.query.merchantIndex
        }


        if (this.$route.query.phonenumber) {
            this.queryParams.phonenumber = this.$route.query.phonenumber
        }

        // if (this.$route.query.categoryList) {
        //     this.queryParams.categoryList = this.$route.query.categoryList
        // }

        if (this.$route.query.name) {
            this.queryParams.name = this.$route.query.name
        }

        if (this.$route.query.isSale) {
            this.queryParams.isSale = this.$route.query.isSale
        }

        if (this.$route.query) {
             if (this.$route.query.beginTime) {
                // console.log("==========",this.$route.query.params)
                // console.log("1",this.$route.query.params.beginTime)
                // console.log(typeof(this.dateRange))
                this.searchDate[0]=this.$route.query.beginTime
                this.searchDate[1]=this.$route.query.endTime
                console.log("-------",this.dateRange)
             }
            
        }


    // this.getList();
    this.categoryTree();
  },
   watch:{
        goodsId(){
            this.getDetail()
        }
    },
  methods: {
    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.$router.go(-1)
            } finally {
                this.saving = false
            }
        },
        async getDetail(){
            if (!this.goodsId) {
                return
            }
            const {data} = await detail(this.goodsId)
            console.log(this.flag)
            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
        },
    categoryTree() {
      categoryTree().then(res => {
        if (res.code == 200) {
          this.categoryList = res.data
          if (this.$route.query.categoryId) {
                    //             this.queryParams.categoryId= [36,37]
                     
                        for(var i=0 ;i<this.categoryList.length;i++){
                            for(var t=0 ;t<this.categoryList[i].childrenCategory.length;t++){
                                if(this.categoryList[i].childrenCategory[t].categoryId == this.$route.query.categoryId){
                                    console.log("=======")
                                    console.log(this.categoryList[i].childrenCategory[t])

                                    this.queryParams.categoryId= [this.categoryList[i].categoryId,this.categoryList[i].childrenCategory[t].categoryId]
                                    console.log(this.queryParams.categoryId)
                                    
                                }
                            }

                            
                            
                     }
                    }
                     this.getList();
        } else {
          this.$message.error("获取分类列表失败")
        }
        console.log(res)
      }).catch(err => {
        this.$message.error("获取分类列表失败")
        console.log(err)
      })
    },
    // handleCategory(value) {
    //   console.log(value)
    //   this.queryParams.categoryId = value[value.length - 1]
    //   console.log(this.queryParams.categoryId)
    // },
    /** 查询待审核列表 */
    getList() {
      var form =this.queryParams
            //判断缓存中数据
            if(this.$route.query.categoryId){
                this.form.categoryId = this.$route.query.categoryId
            }
       this.$store.state.tagsView.visitedViews.forEach(element => {
                if (this.$route.path === element.path) {
                    element.query = this.queryParams
                }
            });

      this.loading = true;
      if(this.searchDate == null){
        this.searchDate = ''
      }
      const [searchBegin, searchEnd] = this.searchDate;
      let sBegin = searchBegin;
      let sEnd = searchEnd;
      if (typeof searchBegin == "undefined") {
         var start = new Date()
                start.setTime(start.getTime()-3600 * 1000 * 24 * 30)
                this.searchDate = [start,new Date()]
                sBegin = this.timeStamp2String(start)
      }
      if (typeof searchEnd == "undefined") {
       sEnd = this.timeStamp2String(new Date())
                this.searchDate=[sBegin,sEnd]
      }

       if (
                    form.categoryId &&
                    form.categoryId.length > 1
                ) {
                    form.categoryId =
                        form.categoryId[
                            form.categoryId.length - 1
                        ];
                }
      this.queryParams.beginTime = sBegin;
      this.queryParams.endTime = sEnd;
      this.queryParams.merchantType = this.merchantType;
      goodsList(this.queryParams)
        .then((response) => {
          console.log(response)
          this.pageList = response.rows;
          this.total = parseInt(response.total);
          this.pageCount=parseInt(response.rows.length)
          console.log(this.pageCount)
        }).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,
        phonenumber: "",
        merchantPhone: "",
        shopState: "",
        promoter: "",
        merchantId: "",
        merchantType: ""
      };
      this.handleQuery();
    },
    /**  查看详情 */
    queryDetails(row) {
      this.isDetail=true
      // this.$message.success("查看详情")
      // this.$router.push("/adminMerchant/pass/info?merchantId=" + primaryId);
      // this.$router.push('/adminMerchant/server/detail?goodsId='+goodsId);
      const goodsId = row.goodsId
      detail(goodsId).then((response) => {
        this.form = response.data
        this.detailOpen=true;
      })
    },

    /** 下架按钮操作 */
    takeOff(row) {
      const goodsId = row.goodsId;
      const name = row.name == null ? "" : row.name;
      this.$confirm(
        '确认下架服务主题为: <span style="font-weight: bold">' +
        name +
        "</span> 的数据项吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          dangerouslyUseHTMLString: true,
          type: "warning",
        }
      ).then(() => {
        goodsTakeOff({
          goodsId: goodsId
        }).then(res => {
          if (res.code == 200) {
            this.$message.success("下架成功！")
            this.getList();
          } else {
            this.$message.error("下架失败！")
          }
        }).catch(err => {
          this.$message.error("操作失败！")
        })
      }).catch(() => {

      });
    },

    takeOn(row) {
      const goodsId = row.goodsId;
      const name = row.name == null ? "" : row.name;
      this.$confirm(
        '确认上架服务主题为: <span style="font-weight: bold">' +
        name +
        "</span> 的数据项吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          dangerouslyUseHTMLString: true,
          type: "warning",
        }
      ).then(() => {
        goodsTakeOn({
          goodsId: goodsId
        }).then(res => {
          if (res.code == 200) {
            this.$message.success("上架成功！")
            this.getList();
          } else {
            this.$message.error("上架失败！")
          }
        }).catch(err => {
          this.$message.error("操作失败！")
        })
      }).catch(() => {

      });
    },

    deleteGoods(row) {
      const goodsId = row.goodsId;
      const name = row.name == null ? "" : row.name;
      this.$confirm(
        '确认删除服务主题为: <span style="font-weight: bold">' +
        name +
        "</span> 的数据项吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          dangerouslyUseHTMLString: true,
          type: "warning",
        }
      ).then(() => {
        deleteGoods(goodsId).then(res => {
          if (res.code == 200) {
            this.$message.success("删除成功！")
            if(this.queryParams.pageNum>1 && this.pageCount==1){
                this.queryParams.pageNum--;
            }
            this.getList();
          } else {
            this.$message.error("删除失败！")
          }
        }).catch(err => {
          this.$message.error("操作失败！")
        })
      }).catch(() => {

      });
    },

    /** 提交按钮 */
    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();
    },

    timeStamp2String(datetime){
           
            var year = datetime.getFullYear();
            var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
            var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
            var hour = datetime.getHours()< 10 ? "0" + datetime.getHours() : datetime.getHours();
            var minute = datetime.getMinutes()< 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
            var second = datetime.getSeconds()< 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
            return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second;
        }
  },
};
</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>
