<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="套餐名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="详细说明" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入套餐详细说明"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收费模式" prop="feeMode">
        <el-select v-model="queryParams.feeMode" @change="handleQuery" clearable placeholder="请选择收费模式">
          <el-option
            v-for="dict in dict.type.suit_fee_mode"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收费类型" prop="feeType">
        <el-select v-model="queryParams.feeType" @change="handleQuery" clearable placeholder="请选择收费类型">
          <el-option
            v-for="dict in dict.type.suit_fee_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="enabled">
        <el-select v-model="queryParams.enabled" @change="handleQuery" clearable placeholder="请选择是否启用">
          <el-option :value="true" label="已启用"/>
          <el-option :value="false" label="未启用"/>
        </el-select>
      </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"
          v-hasPermi="['ss:suit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ss:suit:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ss:suit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="suitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="suitId" width="80"/>
      <el-table-column label="名称" align="center" prop="name"/>
<!--      <el-table-column label="收费模式" align="center" prop="feeMode">-->
<!--        <dict-tag slot-scope="d" :value="d.row.feeMode" :options="dict.type.suit_fee_mode"/>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="收费类型" align="center" prop="feeType" width="160">-->
<!--        <dict-tag slot-scope="d" :value="d.row.feeType" :options="dict.type.suit_fee_type"/>-->
<!--      </el-table-column>-->
      <el-table-column label="价格" align="center" prop="price">
        <template slot-scope="d">{{d.row.price | money}} 元</template>
      </el-table-column>
      <el-table-column label="通电时长" align="center" prop="price" width="100">
        <template slot-scope="d">{{d.row.value}} {{suitTimeUnit(d.row.timeUnit)}}</template>
      </el-table-column>
      <el-table-column label="详细说明" align="center" prop="description" show-overflow-tooltip min-width="200"/>
      <el-table-column label="是否启用" align="center" prop="enabled">
        <el-switch slot-scope="d" v-model="d.row.enabled" @change="(nv) => {onChangeEnabled(d.row, nv)}"/>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="使用次数" align="center" prop="totalCount">
        <template slot-scope="d">{{d.row.totalCount}} 次</template>
      </el-table-column>
      <el-table-column label="所属代理商" align="center" prop="agentId" width="120">
        <user-link slot-scope="d" :id="d.row.agentId" :name="d.row.agentName"/>
      </el-table-column>
      <el-table-column label="应用场所" align="center" prop="storeList" min-width="200">
        <template slot-scope="d">
          <el-tag
            v-for="item in d.row.storeList"
            :key="item.storeId"
            @click="$router.push(`/mch/storeDetail?storeId=${item.storeId}`)"
            style="cursor: pointer; margin: 0 4px 2px 0;"
          >{{item.name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ss:suit:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ss:suit:remove']"
          >删除</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="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <form-col :span="span" label="所属代理" prop="agentId">
            <user-input v-model="form.agentId" :query="{type: SmUserType.SALE}" @change="onChangeAgent"/>
          </form-col>
          <form-col :span="span" label="套餐名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入套餐名称" />
          </form-col>
<!--          <form-col :span="span" label="收费模式" prop="feeMode" >-->
<!--            <el-select v-model="form.feeMode" style="width: 100%" @change="onChangeFeeMode">-->
<!--              <el-option-->
<!--                v-for="option of dict.type.suit_fee_mode"-->
<!--                :key="option.value"-->
<!--                :label="option.label"-->
<!--                :value="option.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </form-col>-->
<!--          <form-col :span="span" label="收费方式" prop="feeType">-->
<!--            <el-select v-model="form.feeType" style="width: 100%">-->
<!--              <el-option-->
<!--                v-for="option of dict.type.suit_fee_type"-->
<!--                :key="option.value"-->
<!--                :label="option.label"-->
<!--                :value="option.value"-->
<!--                :disabled="disabledFeeType(option)"-->
<!--              />-->
<!--            </el-select>-->
<!--          </form-col>-->
          <form-col :span="span" label="价格" prop="price" v-if="[SuitFeeType.TIMING, SuitFeeType.COUNT].includes(form.feeType)">
            <el-input-number v-model="form.price" placeholder="请输入价格(元）" :min="0" :precision="2" controls-position="right" style="width: calc(100% - 2em)"/> 元
          </form-col>
          <form-col :span="span" label="押金" prop="price" v-else>
            <el-input-number v-model="form.price" placeholder="请输入押金(元）" :min="0" :precision="2" controls-position="right" style="width: calc(100% - 2em)"/> 元
          </form-col>
          <form-col :span="span" label="通电时间" prop="value" v-if="form.feeType === SuitFeeType.TIMING">
            <el-input v-model="form.value" placeholder="请输入通电时间" type="number">
              <template #append>
                <el-select v-model="form.timeUnit" style="width: 6em">
                  <el-option
                    v-for="option of dict.type.time_unit"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </template>
            </el-input>
          </form-col>
          <form-col :span="span" label="充值电量" prop="value" v-else-if="form.feeType === SuitFeeType.COUNT">
            <el-input v-model="form.value" placeholder="请输入充值电量" type="number">
              <template #append>度</template>
            </el-input>
          </form-col>
          <form-col :span="span" label="排序" prop="sort">
            <el-input-number v-model="form.sort" placeholder="请输入排序，值越大越靠后" style="width: 100%"/>
          </form-col>
          <form-col :span="span * 2" label="详细说明" prop="description">
            <el-input v-model="form.description" placeholder="请输入详细说明" type="textarea" />
          </form-col>
          <form-col :span="span" label-width="0" v-for="(item, index) of 4" v-if="[SuitFeeType.TIME_COUNT, SuitFeeType.TIME_TIMING].includes(form.feeType)" >
            <el-tooltip effect="dark" :content="`单击设置${item}档电价，双击全部设置为${item}档电价`" placement="top">
              <el-button
                :plain="amountIndex !== index"
                :type="indexStyle[index]"
                @click="handleSetAmountIndex(index)"
                @dblclick.native="handleAllSet(index)">
                {{item}}档电价
              </el-button>
            </el-tooltip>
            <el-input-number v-model="form.gearAmount[index]" controls-position="right" placeholder="请输入电价" :precision="2" style="width: calc(100% - 11em)"/> {{gearUnit}}
          </form-col>
          <form-col :span="24" label-width="0"  v-if="[SuitFeeType.TIME_COUNT, SuitFeeType.TIME_TIMING].includes(form.feeType)">
            <el-row>
              <el-col :span="6" v-for="(item, index) of 24" :key="index" v-if="!refresh">
                <el-button plain style="width: 100%" :type="timeType(index)" @click="handleClickTimeItem(index)">{{index}} 时</el-button>
              </el-col>
            </el-row>
          </form-col>
          <form-col :span="span" label="启用自定义使用率" prop="enableCustomUse" label-width="9em">
            <el-switch v-model="form.enableCustomUse"/>
          </form-col>
          <form-col :span="span" label="自定义使用率" prop="usePoint" label-width="7em">
            <el-input-number v-model="form.usePoint" placeholder="请输入使用率" :min="0" :max="100" :precision="0" controls-position="right" style="width: calc(100% - 1.5em)"/> %
          </form-col>
          <form-col :span="span * 2" label="应用经营场所" prop="storeIds" label-width="7em">
            <store-input v-model="form.storeIds" multiple :before-open="beforeOpenStore" :query="storeQuery"/>
          </form-col>
        </el-row>
      </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>
  </div>
</template>

<script>
import { listSuit, getSuit, delSuit, addSuit, updateSuit } from "@/api/ss/suit";
import DeviceInput from '@/components/Business/Device/DeviceInput.vue'
import { findLabel, isEmpty } from '@/utils'
import UserLink from '@/components/Business/SmUser/UserLink.vue'
import UserInput from '@/components/Business/SmUser/UserInput.vue'
import { $view } from '@/utils/mixins'
import DeviceLink from '@/components/Business/Device/DeviceLink.vue'
import { SmUserType, SuitFeeMode, SuitFeeType } from '@/utils/constants'
import DeptTreeSelect from '@/components/Business/Dept/DeptTreeSelect.vue'
import { mapGetters } from 'vuex'
import StoreInput from '@/components/Business/Store/StoreInput.vue'

export default {
  name: "Suit",
  mixins: [$view],
  dicts: ['time_unit', 'suit_fee_mode', 'suit_fee_type'],
  computed: {
    SmUserType() {
      return SmUserType
    },
    ...mapGetters(['deptId']),
    SuitFeeType() {
      return SuitFeeType
    },
    // 时长单位
    suitTimeUnit() {
      return (unit) => {
        return findLabel(this.dict.type.time_unit, unit);
      }
    },
    // 收费方式禁用的情况：单次收费，不支持分时段
    disabledFeeType() {
      return (option) => {
        return this.isDisabled(this.form.feeMode, option.value);
      }
    },
    // 收费方式单位
    gearUnit() {
      return this.form.feeType === SuitFeeType.TIME_COUNT ? '元 / 度' : '元 / 时 '
    },
    // 时间显示类型
    timeType() {
      return (index) => {
        if(this.form.gearTime[index] == null) {
          return null;
        }
        return this.indexStyle[this.form.gearTime[index]];
      }
    },
    // 店铺查询条件
    storeQuery() {
      return {
        investorAgentId: this.form.agentId
      }
    }
  },
  components: { StoreInput, DeptTreeSelect, DeviceLink, UserInput, UserLink, DeviceInput },
  props: {
    query: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      refresh: false,
      indexStyle: ['success', 'primary', 'warning', 'danger'],
      // 当前设置电价的索引
      amountIndex: null,
      span: 12,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 套餐表格数据
      suitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        name: null,
        feeType: null,
        value: null,
        price: null,
        description: null,
        deleted: null
      },
      // 表单参数
      form: {
        gearAmount: [],
        gearTime: []
      },
      // 表单校验
      rules: {
        agentId: [
          { required: true, message: "所属代理不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
        value: [
          { required: true, message: "通电时间不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        feeMode: [
          { required: true, message: "收费方式不能为空", trigger: "change" }
        ],
        feeType: [
          { required: true, message: "收费类型不能为空", trigger: "change" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }
    this.getList();
  },
  methods: {
    onChangeAgent(user) {
      if (this.form.storeIds != null && this.form.storeIds.length > 0) {
        this.form.storeIds = [];
        this.$message.info("由于更换了代理商，请重新选择应用经营场所")
      }
    },
    beforeOpenStore() {
      if (this.form.agentId == null) {
        this.$message.warning("请先选择代理商")
        return false;
      }
      return true;
    },
    onChangeEnabled(row, nv) {
      updateSuit({suitId: row.suitId, enabled: nv}).then(res => {
        if (res.code !== 200) {
          this.$message.error("修改是否启用失败");
          this.getList();
        }
      })
    },
    isDisabled(feeMode, value) {
      return feeMode === SuitFeeMode.SINGLE &&
        [SuitFeeType.TIME_COUNT, SuitFeeType.TIME_TIMING].includes(value)
    },
    onChangeFeeMode(nv) {
      if(this.isDisabled(nv, this.form.feeType)) {
        this.form.feeType = null;
      }
    },
    // 全部设置为某一个类型
    handleAllSet(index) {
      for(let i = 0; i < 24; i ++) {
        this.form.gearTime[i] = index;
      }
      this.refreshItems();
    },
    handleClickTimeItem(index) {
      if (this.amountIndex != null) {
        this.form.gearTime[index] = this.amountIndex;
        this.refreshItems();
      }
    },
    // 刷新列表
    refreshItems() {
      this.refresh = true;
      this.$nextTick(() => {
        this.refresh = false
      })
    },
    // 处理点击索引按钮
    handleSetAmountIndex(index) {
      if (this.amountIndex === index) {
        this.amountIndex = null;
      } else {
        this.amountIndex = index;
      }
    },
    /** 查询套餐列表 */
    getList() {
      this.loading = true;
      listSuit(this.queryParams).then(response => {
        this.suitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: this.query.userId,
        suitId: null,
        name: null,
        value: null,
        price: null,
        description: null,
        timeUnit: "2",
        feeType: "1",
        feeMode: "1",
        gearAmount: [0,0,0,0],
        gearTime: [],
        deptId: this.deptId,
        sort: 0,
        enableCustomUse: false,
        storeIds: []
      };
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.suitId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.amountIndex = null;
      this.open = true;
      this.title = "添加套餐";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.amountIndex = null;
      const suitId = row.suitId || this.ids
      getSuit(suitId).then(response => {
        let data = response.data;
        data.storeIds = data.storeList.map(item => item.storeId);
        this.form = data;
        this.open = true;
        this.title = "修改套餐";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.suitId != null) {
            updateSuit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSuit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const suitIds = row.suitId || this.ids;
      this.$modal.confirm('是否确认删除套餐编号为"' + suitIds + '"的数据项？').then(function() {
        return delSuit(suitIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ss/suit/export', {
        ...this.queryParams
      }, `suit_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
