<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="服务分类" prop="serviceCategorizeId">
        <el-select v-model="queryParams.serviceCategorizeId" placeholder="请选择服务分类" size="small" clearable style="width: 100%">
          <el-option v-for="(v,i) in typeList" :key="i" :label="v.name" :value="v.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width: 240px">
          <el-option label="上架" :value="true" />
          <el-option label="下架" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @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" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" @sort-change="sortChange">
      <el-table-column type="index" width="55" label="序号" align="center">
        <template slot-scope="scope">
          <div>
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="服务ID" align="center" prop="id" width="120" />
      <el-table-column label="服务分类" align="center" prop="serviceCategorizeName" />
      <el-table-column label="服务名称" align="center" prop="name" />
      <el-table-column label="价格（元）" align="center" prop="sellingPrice" />
      <el-table-column label="单位" align="center" prop="serviceUnit">
        <template slot-scope="{row}">
          <div v-for="(v,i) in serviceUnitList" :key="i" v-if="v.code == row.serviceUnit">{{v.value}}</div>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" align="center" prop="status">
        <template slot-scope="{row}">
          <el-tag type="success" v-if="row.status">上架</el-tag>
          <el-tag type="danger" v-if="!row.status">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="140">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime,'{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row,'show')">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,'edit')">修改</el-button>
          <el-button size="mini" type="text" @click="setStatus(scope.row)">{{scope.row.status?'下架':'上架'}}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" v-if="!scope.row.status" @click="handleDelete(scope.row)">删除</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" />

  </div>
</template>

<script>
import { serviceProductPage, serviceCategorizeList, serviceProductSetStatus, serviceProductDel, serviceProductEnum } from "@/api/service.js";
export default {
  data () {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [1],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        businessName: undefined,
        businessProductCategoryId: undefined,
        status: undefined,
        giftPoints: undefined
      },
      daterangeCreateTime: [],
      typeList: [],
      serviceUnitList: []
    }
  },
  created () {
    let queryParams = localStorage.getItem('queryParams');
    if (queryParams) {
      this.queryParams = JSON.parse(queryParams);
      localStorage.setItem('queryParams', '')
    }
    this.getList();
    this.getTypeList();
    this.getServiceUnitList();
  },
  methods: {
    sortChange (e) {
      this.queryParams.sortOrder = Boolean(e.order == "ascending");
      this.handleQuery()
    },
    // 获取服务单位列表
    getServiceUnitList () {
      serviceProductEnum().then(res => {
        this.serviceUnitList = res.data.serviceUnit
      })
    },
    // 获取服务分类列表
    getTypeList () {
      serviceCategorizeList().then((res) => {
        this.typeList = res.data;
      });
    },
    /** 上下架按钮操作 */
    setStatus (row) {
      const ids = row.id;
      let statusText = row.status ? '下架' : '上架';
      this.$modal.confirm('是否确认' + statusText + '服务名称为"' + row.name + '"的数据项？').then(() => {
        this.loading = true;
        return serviceProductSetStatus(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess(statusText + "成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    getList () {
      this.loading = true;
      this.queryParams["startTime"] = undefined;
      this.queryParams["endTime"] = undefined;
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams["startTime"] = this.daterangeCreateTime[0];
        this.queryParams["endTime"] = this.daterangeCreateTime[1];
      }
      serviceProductPage(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCnAreaTree () {
      cnAreaTree().then(res => {
        this.areaTrea = res.data?.children
      })
    },
    // 省市区选择
    handleChange (value) {
      this.queryParams.provinces = value;
      this.queryParams.provinceCode = value[0];
      this.queryParams.provinceName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[0];
      this.queryParams.cityCode = value[1];
      this.queryParams.cityName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[1];
      this.queryParams.areaCode = value[2];
      this.queryParams.areaName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[2];
    },
    handleAdd () {
      this.$router.push({
        path: '/service/details',
      })
    },
    goCouponCodeDatabase (row) {
      if (row.codeType == 1) {
        this.$router.push({
          path: '/goods/couponCodeDatabase',
          query: {
            productId: row.businessProductId,
            title: row.title,
            queryParams: JSON.stringify(this.queryParams)
          }
        })
      }
    },
    handleUpdate (row, type) {
      this.$router.push({
        path: '/service/details',
        query: {
          id: row.id,
          type: type || 'edit',
          queryParams: JSON.stringify(this.queryParams)
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除服务名称为"' + row.name + '"的数据项？').then(() => {
        this.loading = true;
        return serviceProductDel(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
  }
}
</script>

<style lang='scss' scoped>
.active {
  color: #1890ff;
  cursor: pointer;
}
</style>