<template>
  <div class="fatigue-control-wrap">
    <bread-crumb :curmbFirst="curmbFirst"></bread-crumb>
    <div class="component-content screenSet" id="screenSet">
      <el-form ref="form" :model="searchReq" label-width="80px" style="overflow: hidden;">
        <el-form-item label="策略名称" prop="startDate" class="diagnose-select-style" style="float: left;">
          <el-select v-model="searchReq.strategyCode" filterable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.strategyCode"
              :label="item.name"
              :value="item.strategyCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="修改时间" style="width: 470px; float: left;">
          <el-date-picker
            v-model="duringTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <div style="float: right; margin-right: 28px;">
          <el-button type="primary" style="float: left; margin: 0 10px 10px 0;" @click="handleSearchClick">搜索</el-button>
          <el-button type="primary" style="float: left; margin: 0 10px 10px 0;" @click="handleRefresh">刷新</el-button>
        </div>
        <div style="overflow: hidden; clear: both; float: right; margin-right: 28px;">
          <el-button type="primary" style="float: left; margin: 0 10px 10px 0;" @click="handleAddOrEdit('add')">添加</el-button>
        </div>
      </el-form>
      <div style="padding: 0 40px;">
        <el-table
          :data="tableData"
          border
          style="width: 100%;">
          <el-table-column
            align="center"
            prop="name"
            label="名称"
            >
          </el-table-column>
          <el-table-column
            align="center"
            prop="toLimit"
            label="频次控制"
            >
            <template slot-scope="scope">
              {{scope.row.toLimit + '次/天' }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="修改时间"
            >
            <template slot-scope="scope">
              {{scope.row.modifyTime ? scope.row.modifyTime.year + '-' + scope.row.modifyTime.monthValue + '-' + scope.row.modifyTime.dayOfMonth : '-'}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="modifyName"
            label="操作人"
            >
          </el-table-column>
          <el-table-column
            align="center"
            prop="strategyNameShow"
            label="策略组"
            :show-overflow-tooltip="true"
           >
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
           >
            <template slot-scope="scope">
              <el-button @click="handleAddOrEdit('edit', scope.row)" type="text" >编辑</el-button>
              <el-button @click="showDeleteModal(scope.row)" type="text" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchReq.pageNo"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="searchReq.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRows">
        </el-pagination>
      </div>
      </div>
      <!-- 添加modal 弹窗 -->
      <el-dialog
        :visible.sync="centerDialogVisible"
        :close-on-click-modal="false"
        v-if="centerDialogVisible"
        width="700px"
        @close="handleCancel"
        center>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="名称" prop="name" style="width: 600px;">
            <el-input 
              type="text" 
              placeholder="请输入" 
              maxlength="30" 
              show-word-limit 
              v-model="ruleForm.name">
            </el-input>
          </el-form-item>
          <el-form-item label="频次" prop="toLimit" style="width: 600px;">
            <el-input 
              v-model.number="ruleForm.toLimit"
              type="text"
              maxlength="3" 
              placeholder="请输入" 
              style="width: 100px;">
            </el-input>
            <p style="display: inline-block; margin-left: 10px;">次/天</p>            
          </el-form-item>
          <el-form-item label="策略组" prop="strategyCodeList">
            <el-select 
              v-model="ruleForm.strategyCodeList" 
              multiple
              placeholder="请选择策略组名称（多选）" style="width: 500px;">
              <el-option v-for="item in strategyList" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="confirmAddOrEdit('ruleForm')">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 删除 弹窗 -->
      <el-dialog
        title="删除"
        :close-on-click-modal="false"
        :visible.sync="deleteDialogVisible"
        width="400px"
        center>
        <span>确认删除？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmDelete">确 定</el-button>
        </span>
      </el-dialog>

    </div>
  </div>
</template>
<script>
  import { openLoading, closeLoading } from "../../utils/utils";
  import BreadCrumb from "../../components/breadcrumb.vue";
  export default {
    components: {
      BreadCrumb,
    },
    data() {
      var checkToLimit = (rule, value, callback) => {
        if(typeof value != 'undefined' && value == 0){
          return callback(new Error('频次范围：1-100'));
        };
        if (!value) {
          return callback(new Error('频次不能为空'));
        }else{
          if (!Number.isInteger(value)) {
            this.ruleForm.toLimit = '';
            callback(new Error('频次必须为数字值'));
          } else {
            if (value < 1 || value > 100) {
              callback(new Error('频次范围：1-100'));
            } else {
              callback();
            }
          }
        }
      };
      return {
        curmbFirst: "疲劳度控制",
        duringTime: "",
        ruleForm: {             // 新增/编辑 数据
          name: '',             // 名称
          toLimit: '',          // 频次
          strategyCodeList: '', // 策略组（策略组 codelist）
        },
        rules: {
          name: [
            { required: true, message: '请填写名称', trigger: 'blur' },
          ],
          toLimit: [
            { required: true, message: '请填写频次', trigger: 'blur' },
            { validator: checkToLimit },
          ],
          strategyCodeList: [
            { required: true, message: '请选择策略组', trigger: 'blur' },
          ]
        },
        isCreate: true,
        centerDialogVisible: false,
        tableData: [],
        totalRows: 0,  // 总页数 
        inputSearchName: '',
        searchReq: {   // 疲劳度列表 请求参数
          strategyCode: '',
          pageNo: 1,
          pageSize: 10,
          startTime: '',
          endTime: '',
        },
        strategyList: [],
        deleteDialogVisible: false,
        rowData: {},
        loading: false,
        options: [],

      }
    },
    created() {
      this.getStrategyNameList();
      this.getList();
    },
    methods: {
      getStrategyNameList() {
        openLoading(this);
        this.GET("raytheon/strategy/pullSelect", {}).then(res => {
          closeLoading(this);
          if(res && res.code && res.code == '000000'){
            // console.log('get 策略下拉列表>>>>> ', res);  
            this.options = res.data;
          }else{
            this.$message({
              message: '接口请求失败',
              type: 'warning'
            });
          }
        });
      },
      handleCancel() {
        this.resetForm('ruleForm');
        this.centerDialogVisible = false;
        this.initRuleFormData();
      },
      initRuleFormData() {
        this.ruleForm = {
          name: '',             // 名称
          toLimit: '',          // 频次
          strategyCodeList: '', // 策略组（策略组 codelist）
        };
      },
      confirmAddOrEdit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.isCreate == true){  // 创建策略时
              this.handleAddSave();
            }else{  // 编辑时
              this.handleEditSave();
            }
            
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      handleAddSave() {
        let req = this.ruleForm;
        openLoading(this);
        this.POST('raytheon/fatigueControlInfo/save', req).then((res) => {
            closeLoading(this);
            if( res && res.code && res.code == '000000') {
              // console.log('>>>>>> 新增 编辑 OK ', req);
              this.getList();
              this.centerDialogVisible = false;
              this.initRuleFormData();

            }else{
              this.$message({
                message: '接口请求失败',
                type: 'warning'
              });
            }
        })
      },
      handleEditSave() {
        let req = this.ruleForm;
        openLoading(this);
        this.POST('raytheon/fatigueControlInfo/update', req).then((res) => {
            closeLoading(this);
            if( res && res.code && res.code == '000000') {
              // console.log('>>>>>> 新增 编辑 OK ', req);
              this.getList();
              this.centerDialogVisible = false;
              this.initRuleFormData();
            }else{
              this.$message({
                message: '接口请求失败',
                type: 'warning'
              });
            }
        })
      },
      
      handleSearchClick() {
        this.searchReq.pageNo = 1;
        this.getList();
      },
      handleRefresh() {
        let options = {
          isRefresh: true
        };
        this.getList(options);
      },
      handleSizeChange(val){
        this.searchReq.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.searchReq.pageNo = val;
        this.getList();
      },
      getList(options) {
        if( options && options.isRefresh ){  // 刷新 请求参数置为默认
          this.searchReq = {
            strategyCode: '',
            pageNo: 1,
            pageSize: 10,
            startTime: '',
            endTime: '',
          };
          this.duringTime = '';
        }else{
          // 时间获取
          // console.log('this.duringTime',this.duringTime);
          if(this.duringTime!=='' && this.duringTime!==null) {
            this.searchReq.startTime = this.duringTime[0].getTime();
            this.searchReq.endTime = this.duringTime[1].getTime();
          } else {
            this.searchReq.startTime = '';
            this.searchReq.endTime = '';
          }
        }

        let req = this.searchReq;
        openLoading(this);
        this.GET("raytheon/fatigueControlInfo/list", req).then(res => {
          closeLoading(this);
          if(res && res.code && res.code == '000000'){
            // console.log('get 策略列表>>>>> ', res);  
            if (res.data) {
              this.totalRows = res.data.total;
            }
            if(res.data && res.data.list && res.data.list.length > 0){
              this.tableData = res.data.list;
            }else{
              this.tableData = [];
            }
          }else{
            this.$message({
              message: '接口请求失败',
              type: 'warning'
            });
          }
        });
      },
      handleAddOrEdit(status, rowData) {
        // isCreate
        this.centerDialogVisible = true;
        let req = {};
        
        if(status && status == 'add'){  // 添加
          this.isCreate = true;
          this.ruleForm = {
            name: '',             // 名称
            toLimit: '',          // 频次
            strategyCodeList: '', // 策略组（策略组 codelist）
          };
          req = {
            code: '0'  // 添加时 code传0
          };
        }else{  // 编辑
          this.isCreate = false;
          const { code, name, toLimit, strategyCodeList } = rowData;
          this.ruleForm = {
            code,  // 编辑时 多传一个code
            name,
            toLimit,
            strategyCodeList,
          };
          req = {
            code,
          };
        }
        openLoading(this);
        this.GET("raytheon/strategy/pullList", req).then(res => {
          closeLoading(this);
          if(res && res.code && res.code == '000000'){
            console.log('获取疲劳度策略组下拉列表>>> ', res.data)
            this.strategyList = res.data;
          }else{
            this.$message({
              message: '接口请求失败',
              type: 'warning'
            });
          }
        });
      },

      showDeleteModal(rowData) {
        this.deleteDialogVisible = true;
        this.rowData = rowData;
      },
      confirmDelete() {
        let req = {
          code: this.rowData.code
        };
        openLoading(this);
        this.POST('raytheon/fatigueControlInfo/delete', req).then((res) => {
            closeLoading(this);
            if( res && res.code && res.code == '000000') {
              console.log('>>>>>> 新增 编辑 OK ', req);
              this.deleteDialogVisible = false;
              this.getList();
            }else{
              this.$message({
                message: '接口请求失败',
                type: 'warning'
              });
            }
        })
      },
    },
  }
</script>  
<style lang="scss">
  .fatigue-control-wrap{
    .el-form-item .el-form-item__label{
      font-size: 14px;
    }
    .component-content{
      margin-top: 60px;
      padding: 10px;
      background: #fff;
    }
    .el-date-editor--daterange.el-input__inner{
      width: 380px !important;
    }
    .pagination{
      margin: 20px 0;
      text-align: right;
    }
  }
</style>