<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="deviceId" v-if="deviceId == null">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="suitList" @selection-change="handleSelectionChange">
      <el-table-column type="index" width="55" align="center" label="#" />
      <el-table-column label="套餐名称" align="center" prop="name" />
      <el-table-column label="通电时间" align="center" prop="value" >
        <template slot-scope="d">{{d.row.value}} {{suitTimeUnit(d.row.timeUnit)}}</template>
      </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="description" show-overflow-tooltip/>
      <el-table-column label="应用设备" align="center" prop="deviceList" min-width="200">
        <template slot-scope="d">
          <template v-for="(item, index) in d.row.deviceList"  >
            <device-link type="tag" style="margin-right: 4px" :key="index" :id="item.deviceId" :text="`${item.deviceName}(${item.deviceNo})`"/>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @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"
    />

    <!-- 添加或修改套餐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="通电时间" prop="value">
          <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>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" placeholder="请输入价格(元）" :min="0" :precision="2"/> 元
        </el-form-item>
        <el-form-item label="详细说明" prop="description">
          <el-input v-model="form.description" placeholder="请输入详细说明" type="textarea" />
        </el-form-item>
        <el-form-item label="应用设备" prop="deviceIds">
          <device-input v-model="form.deviceIds" multiple/>
        </el-form-item>
      </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 DeviceInput from '@/components/Business/Device/DeviceInput.vue'
import { findLabel } from '@/utils'
import { mchAddSuit, mchDelSuit, mchGetSuit, mchListSuit, mchUpdateSuit } from '@/api/mch/suit'
import DeviceLink from '@/components/Business/Device/DeviceLink.vue'

export default {
  name: "MchSuit",
  dicts: ['time_unit'],
  computed: {
    // 时长单位
    suitTimeUnit() {
      return (unit) => {
        return findLabel(this.dict.type.time_unit, unit);
      }
    }
  },
  components: { DeviceLink, DeviceInput },
  props: {
    deviceId: {
      type: String,
      default: null,
    }
  },
  data() {
    return {
      // 遮罩层
      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: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "设备不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
        value: [
          { required: true, message: "通电时间不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
      }
    };
  },
  mounted() {
    this.queryParams.deviceId = this.deviceId;
    this.getList();
  },
  methods: {
    /** 查询套餐列表 */
    getList() {
      this.loading = true;
      mchListSuit(this.queryParams).then(response => {
        this.suitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        suitId: null,
        deviceId: this.deviceId,
        name: null,
        feeType: null,
        value: null,
        price: null,
        description: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        deleted: null,
        timeUnit: '3'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    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.open = true;
      this.title = "添加套餐";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const suitId = row.suitId || this.ids
      mchGetSuit(suitId).then(response => {
        let data = response.data;
        data.deviceIds = data.deviceList.map(item => item.deviceId);
        this.form = data;
        this.open = true;
        this.title = "修改套餐";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.suitId != null) {
            mchUpdateSuit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            mchAddSuit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm(`是否确认删除套餐 "${row.name}" ?`).then(function() {
        return mchDelSuit(row.suitId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ss/suit/export', {
        ...this.queryParams
      }, `suit_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
