<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" ref="filter-container">
      <el-form :rules="rules4Query" ref="queryForm" :inline="inline" :model="listQuery" label-width="100px">
            <el-form-item label="车辆编码">
              <el-input v-model="listQuery.vehicleCode" placeholder="请输入车辆编码"></el-input>
            </el-form-item>
            <el-form-item label="车牌号">
              <el-input v-model="listQuery.numberPlate" placeholder="请输入车牌号"></el-input>
            </el-form-item>
            <el-form-item label="预警消息类型">
              <el-select class="filter-item" v-model="listQuery.type" placeholder="请选择预警消息类型">
                <el-option :key="undefined" label="无" :value="undefined"></el-option>
                <el-option v-for="(val, key, index) in vehicleWarningMsgType " :key="val.code" :label="val.val"
                           :value="val.code"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="颜色预警">
              <el-select class="filter-item" v-model="listQuery.colorType" placeholder="请选择颜色预警">
                <el-option :key="undefined" label="无" :value="undefined"></el-option>
                <el-option v-for="(val, key, index) in vehicleWarningMsgColorType " :key="val.code" :label="val.val"
                           :value="val.code"></el-option>
              </el-select>
            </el-form-item>
            <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
            <el-button class="filter-item" v-if="vehicleWarningMsg_btn_add" style="margin-left: 10px;"
                       @click="handleCreate"
                       type="primary" icon="edit">添加
            </el-button>
            <el-button class="filter-item" type="primary" v-waves @click="reloadPage">重置</el-button>
      </el-form>

    </div>


    <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row
              style="width: 100%">

      <el-table-column width="100" align="center" label="车辆编码">
        <template slot-scope="scope">
          <span>{{scope.row.vehicleCode}}</span>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" label="车牌号">
        <template slot-scope="scope">
          <span>{{scope.row.numberPlate}}</span>
        </template>
      </el-table-column>
      <el-table-column width="180" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" label="颜色预警">
        <template slot-scope="scope">
          <span v-if="scope.row.colorType==1">红色预警</span>
          <span v-if="scope.row.colorType==2">蓝色预警</span>
          <span v-if="scope.row.colorType==3">黄色预警</span>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" label="预警消息类型">
        <template slot-scope="scope">
          <span>{{getTypeName(scope.row.type)}}</span>
        </template>
      </el-table-column>

      <el-table-column width="500" align="center" label="预警消息内容">
        <template slot-scope="scope">
          <span>{{scope.row.msg}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="备注">
        <template slot-scope="scope">
          <span>{{scope.row.remark}}</span>
        </template>
      </el-table-column>



      <el-table-column align="center" label="操作" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button  v-if="scope.row.status == 1&&vehicleInfo_btn_upkeep" size="small" class="el-button el-button--text el-button--small" style="color:red;" @click="handleDeal(scope.row)">处理
          </el-button>
          <el-button v-if="scope.row.status == 5&&vehicleInfo_btn_upkeepEnd" size="small" class="el-button el-button--text el-button--small" @click="upkeepEndHandler(scope.row)">
            保养结束
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>


    <!--  增加/修改弹出框  -->
    <el-dialog title="保养" :visible.sync="dialogFormVisible">

      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="消息内容" prop="remark">
          <el-input type="textarea" :rows="5" v-model="form.msg" placeholder="请输入消息内容"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :rows="5" v-model="form.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form4Apply')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 车辆保养弹窗 -->
    <upkeepDialog v-if="upkeepDialogVisible" :upkeepRow="upkeepRow" v-on:upkeepDialogEvent = "upkeepDialogEvent"></upkeepDialog>
  </div>
</template>

<script>
  import upkeepDialog from '../../modal/upkeepDialogVisible'
  import {
    page,
    addObj,
    getObj,
    dealObj
  } from 'api/vehicle/vehicleWarningMsg/';
  import {
    getAllUpkeepItem
  } from 'api/vehicle/upkeep';

  import rsCode from '../../../utils/rsCode';

  import {mapGetters} from 'vuex';
  import {
    getAllCompany,
    getAll
  } from 'api/base_info/branch_company/';
  import {
    upkeepEndVehicle,
    upkeepVehicle
  } from 'api/vehicle/active';
  export default {
    name: 'vehicleInfo',
    components: {
      upkeepDialog
    },
    data() {
      return {
        vehicleWarningMsgColorType:[
          {
            code:1,
            val:'红色预警'
          },{
            code:2,
            val:'蓝色预警'
          },{
            code:3,
            val:'黄色预警'
          }
        ],
        upkeepRow: {},//保养数据
        form: {
          msg: undefined,
          remark: undefined
        },
        upkeepForm: {
          vehicleId: null,
          state1: "",
          numberPlate: null,
          operator: null,
          date: null,
          mileage: null,
          amount: null,
          approvers: null,
          branchCompanyId: null,
          upkeepItems: []
        },
        rules: {
          name: [
            {
              type: 'string',
              required: true,
              message: '请输入消息内容',
              trigger: 'blur'
            },
            {
              min: 0,
              max: 2000,
              message: '长度小于 2000 个字符',
              trigger: 'blur'
            }
          ],
          remark: [
            {
              min: 0,
              max: 2000,
              message: '长度小于 2000 个字符',
              trigger: 'blur'
            }
          ]
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          numberPlate: undefined,
          vehicleCode: undefined,
          type: undefined,
          colorType:undefined,
        },
        allCompanies: {},
        allCompaniesArr: [],
        dialogFormVisible: false,
        rules4Query: undefined,
        upkeepDialogVisible: false,
        inline: true,
        textMap: {
          create: '创建'
        },
        allUpkeepItems: null,
        dialogStatus: undefined,
        tableKey: 0,
        vehicleWarningMsg_btn_add: false,//增加自定义预警
        vehicleInfo_btn_upkeep: false,//处理预警消息
        vehicleInfo_btn_upkeepEnd: false,//保养结束
      }
    },
    created() {
      let query =  localStorage.getItem("vehicleWarningMsg");
      if(query !="null" && query){
        this.listQuery = JSON.parse(query);
      }
      this.getList();
      getAll()
        .then(response => {
          this.allCompaniesArr = response.data;
        })
      getAllCompany(codeAndBranchCompany => {
        this.allCompanies = codeAndBranchCompany;
      });
      getAllUpkeepItem().then(response => {
        this.allUpkeepItems = response.data;
      });
      this.vehicleWarningMsg_btn_add=this.elements['vehicleWarningMsg:btn_add'];//增加自定义预警
      this.vehicleInfo_btn_upkeep = this.elements['vehicleInfo:btn_upkeep'];//处理预警消息
      this.vehicleInfo_btn_upkeepEnd= this.elements['vehicleInfo:btn_upkeepEnd'];//保养结束
    },
    computed: {
      ...mapGetters([
        'elements',
        'vehicleWarningMsgType'
      ])
    },
    methods: {
      /**
       * 重置
       * */
      reloadPage() {
        this.state1='';
        this.listQuery = {
          page: 1,
          limit: 10,
          numberPlate: undefined,
          vehicleCode: undefined,
          type: undefined,
          colorType:undefined,
        };
        if(this.listQuery){
          localStorage.setItem("vehicleWarningMsg", JSON.stringify(this.listQuery));
        }
        this.getList();
      },
      getTypeName: function(type) {
        if (this.$utils.isEmpty(this.vehicleWarningMsgType[type])) {
          return '未知';
        }
        return this.vehicleWarningMsgType[type].val;
      },
      getList() {
        this.listLoading = true;
        page(this.listQuery).then(response => {
          let totalCountRs = undefined;
          let listRs = undefined;
          if (!this.$utils.isEmpty(response.data.data) && this.$utils.isInteger(response.data.totalCount)) {
            listRs = response.data.data;
            totalCountRs = response.data.totalCount;
          }
          this.listLoading = false;
          this.list = listRs;
          this.total = totalCountRs;
        })
      },
      handleFilter() {
        let t = this;
        this.listQuery.page = 1
        this.$refs.queryForm.validate(valid => {
          if (valid) {
            if(t.listQuery){
              localStorage.setItem("vehicleWarningMsg", JSON.stringify(t.listQuery));
            }
            this.getList();
          } else {
            return false;
          }
        });
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        if(this.listQuery){
          localStorage.setItem("vehicleWarningMsg", JSON.stringify(this.listQuery));
        }
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        if(this.listQuery){
          localStorage.setItem("vehicleWarningMsg", JSON.stringify(this.listQuery));
        }
        this.getList();
      },
      /**
       * 保养modal传递回来的数据
       * */
      upkeepDialogEvent(e){
        this.upkeepDialogVisible = e;
        this.getList();
      },
      handleCreate() {
        this.resetTemp();
        this.dialogStatus = 'create';
        this.dialogFormVisible = true;
      },
      /**
       * 保养结束
       * */
      upkeepEndHandler(row) {
        console.dir(row);
        this.$confirm('此操作将结束保养, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          upkeepEndVehicle({
            vehicleId: row.vehicleId
          }).then(() => {
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 2000
            });
            this.getList();
          });
        });
      },
      /**
       * 操作-处理
       * @param row
       */
      handleDeal(row) {
        this.upkeepRow = row;
        this.upkeepDialogVisible = true;
      },
      cleanUpkeepForm() {
        this.upkeepForm = {
          state1: "",
          vehicleId: null,
          numberPlate: null,
          operator: null,
          date: null,
          mileage: null,
          amount: null,
          approvers: null,
          branchCompanyId: null,
          upkeepItems: []
        }
      },
      create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            addObj(this.form)
              .then(response => {
                if (response.code === rsCode.RS_CODE_SUC) {
                  this.dialogFormVisible = false;
                  this.getList();
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  });
                } else {
                  this.$notify({
                    title: '失败',
                    message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                    type: 'error',
                    duration: 2000
                  });
                }
              });
          } else {
            return false;
          }
        });
      },
      cancel(formName) {
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();
      },
      resetTemp() {
        this.form = {
          msg: undefined,
          remark: undefined
        };
      }
    }
  }
</script>
