<template>
  <div class="app-container contract-wrap">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计价类型" prop="contractType">
        <el-select v-model="queryParams.contractType" placeholder="请选择计价类型" clearable size="small">
          <el-option
            :label="keys"
            v-for="(keys, vals) in contractTypeOption"
            :key="keys"
            :value="vals"
          />
        </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="['iot:contract:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:contract:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList">
      <el-table-column type="index" label="序号" align="center" :index="indexFormatter" width="80px"></el-table-column>
      <el-table-column label="合同名称" align="left" prop="contractName" />
      <el-table-column
        label="计价类型"
        align="left"
        prop="contractType"
        :formatter="contractTypeFormatter"
      />
      <el-table-column
        label="状态"
        align="center"
        width="150px"
        prop="status"
        :formatter="statusFormatter"
      />
      <el-table-column
        label="操作"
        align="center"
        width="200px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDestail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:contract:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:contract: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
      class="eldialog-wrap"
      :title="title"
      :visible.sync="open"
      width="720px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="form" :disabled="tempType === 'destail'" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="合同名称:" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计价类型:" prop="contractType">
              <el-select
                v-model="form.contractType"
                style="width: 100%;"
                @change="contractTypeChange"
                placeholder="请选择计价类型"
              >
                <el-option
                  :label="keys"
                  v-for="(keys, vals) in contractTypeOption"
                  :key="keys"
                  :value="vals"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态:">
              <el-switch
                v-model="form.status"
                active-value="0"
                inactive-value="1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="合同规则:" prop>
          <el-button size="mini" type="primary" @click="handelAddRule">添加规则</el-button>
          <div class="contract-gz-wrap" v-for="(item, index) in form.priceContractRuleList" :key="item.guid">
            <time-picker-wrap
              :priceList="item"
              :contractType="form.contractType"
              :tempIndex="item.guid"
              :delshow="form.priceContractRuleList.length >= 2"
              :nodeMaxTime="returnMinTime(index)"
              :nodeMaxVal="returnMaxVal(index)"
              @resultEvent="resultEvent"
              @delEvent="delEvent"
            ></time-picker-wrap>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" v-show="tempType !== 'destail'" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listContract,
  getContract,
  delContract,
  addContract,
  updateContract,
  exportContract
} from "@/api/iot/contract";

import TimePickerWrap from "./profile/timePicker";

const contractTypeOption = {
  PEAK_VALLEY: "峰谷时段计价",
  LADDER: "阶梯计价"
};

export default {
  name: "Contract",
  components: {
    TimePickerWrap
  },
  data() {
    return {
      contractTypeOption,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电价合同表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractName: null,
        contractType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractName: [
          { required: true, message: "请填写合同名称", trigger: "blur" }
        ],
        contractType: [
          { required: true, message: "请选择合同类型", trigger: "blur" }
        ]
      },
      tempType: ''
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getGuid() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(
        c
      ) {
        var r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
    contractTypeFormatter(row) {
      return this.contractTypeOption[row.contractType];
    },
    statusFormatter(row) {
      return row.status === "0" ? "启用" : "禁用";
    },
    resultEvent(data) {
      for (var i = 0; i < this.form.priceContractRuleList.length; i++) {
        if (this.form.priceContractRuleList[i]["guid"] === data.index) {
          this.form.priceContractRuleList[i] = data.result;
          this.$forceUpdate();
        }
        this.form.priceContractRuleList[i]['ruleNum'] = i + 1;
      }
      this.$forceUpdate();
    },
    returnMinTime(index) {
      var time =
        index >= 1
          ? this.form.priceContractRuleList[index - 1].maxTime
          : "00:00:00";
      return time;
    },
    returnMaxVal(index) {
      var time =
        index >= 1 ? this.form.priceContractRuleList[index - 1].maxVal : 0;
      return time;
    },
    delEvent(data) {
      for (var i = 0; i < this.form.priceContractRuleList.length; i++) {
        if (this.form.priceContractRuleList[i]["guid"] === data.index) {
          this.form.priceContractRuleList.splice(i, 1);
          this.$forceUpdate();
          break;
        }
      }
    },
    handelAddRule() {
      this.form.priceContractRuleList.push({
        maxTime: "",
        maxVal: "",
        minTime: "",
        minVal: "",
        ruleName: "",
        ruleNum: null,
        unitPrice: "",
        guid: this.getGuid()
      });
    },
    contractTypeChange(val) {
      this.form.priceContractRuleList = [];
      this.form.priceContractRuleList.push({
        maxTime: "",
        maxVal: "",
        minTime: "",
        minVal: "",
        ruleName: "",
        ruleNum: null,
        unitPrice: "",
        guid: this.getGuid()
      });
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    /** 查询电价合同列表 */
    getList() {
      this.loading = true;
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        contractName: null,
        contractType: "PEAK_VALLEY",
        status: "0",
        remark: null,
        priceContractRuleList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加电价合同";
      this.tempType = 'add'
      this.form.priceContractRuleList.push({
        maxTime: "",
        maxVal: "",
        minTime: "",
        minVal: "",
        ruleName: "",
        ruleNum: null,
        unitPrice: "",
        guid: this.getGuid()
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const contractId = row.contractId || this.ids;
      getContract(contractId).then(response => {
        this.form = response.data;
        var arr = [];
        response.data.priceContractRuleList.forEach(v => {
          arr.push(Object.assign(v, { guid: this.getGuid() }));
        });
        this.form.priceContractRuleList = arr || [];
        this.open = true;
        this.tempType = 'update'
        this.title = "修改电价合同";
      });
    },
    handleDestail(row) {
      this.reset();
      const contractId = row.contractId || this.ids;
      getContract(contractId).then(response => {
        this.form = response.data;
        var arr = [];
        response.data.priceContractRuleList.forEach(v => {
          arr.push(Object.assign(v, { guid: this.getGuid() }));
        });
        this.form.priceContractRuleList = arr || [];
        this.tempType = 'destail'
        this.open = true;
        this.title = "电价合同详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.contractId != null) {
            updateContract(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContract(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delContract(contractIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有电价合同数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportContract(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    }
  }
};
</script>
<style lang="scss">
.contract-gz-wrap {
  min-height: 50px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  top: 15px;
  border: 1px solid #a9a6a6;
  margin-bottom: 15px;
  left: -70px;
  width: calc(100% + 70px);
  padding: 10px;
}
</style>
