<template>
  <!-- 车辆管理 -->
  <div>
    <actionBar menuTitle="车辆管理" :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm"
      @openModel="openModel" @searchProtocol="searchProtocol"></actionBar>
    <tables :key="Math.random()" :suspension="true" :tableList="tableList" :tableData="tableData"
      @buttonData="buttonData"></tables>
    <!-- 分页 -->
    <div class="paging_bottom" v-if="Pagination.Total">
      <pagination :total="Pagination.Total" :currentPage="Pagination.PageIndex" @changeSize="changeSize"
        @changeCurrent="changeCurrent">
      </pagination>
    </div>
    <el-dialog :title="shopTitle" :visible.sync="shopDialogVisible" :width="dialogWidth" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm" labelWidth="150px"
        @handleScroll="handleScroll" @remoteMethod="remoteMethod"></forms>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="shopDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="carLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getCar,
    getCarDetails,
    addCar,
    putCar,
    delCar,
    bindTruckUser
  } from '@/api/car'
  import {
    getUser
  } from '@/api/user'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import {
    rules,
    tableRules,
    vehicle
  } from "./carTable.js";
  export default {
    components: {
      actionBar,
      tables,
      pagination,
      forms
    },
    data() {
      return {
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
          Total: 0,
        },
        formList: [{
          type: 'input',
          label: '车牌号',
          field: 'carNo',
          placeholder: '请输入车牌号查找',
        }, {
          type: 'picker',
          label: '道路运输证有效期',
          field: 'transportTime',
          placeholder: '道路运输证有效期',
        }, ],
        searchRuleForm: {
          carNo: '',
          transportTime: [],
        },
        operateList: [{
          type: 'add',
          title: '添加车辆',
          icon: 'el-icon-plus',
        }],
        tableList: tableRules(),
        tableData: [],
        shopDialogVisible: false,
        shopTitle: '添加',
        formRuleList: [],
        ruleForm: {},
        searchValue: {},
        operationType: '',
        carLoading: false,
        enterpriseId: '',
        dialogWidth: '60%',
        page: 1,
        staffName: '',
        limitNo: true,
        carNo: '',
      }
    },
    mounted() {
      this.getList()
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.searchValue = value
        if (value.transportTime) {
          this.searchValue.startTransportTime = value.transportTime[0]
          this.searchValue.endTransportTime = value.transportTime[1]
          delete this.searchValue.transportTime
        }
        this.getList()
      },
      // 获取车辆列表
      getList() {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          ...this.searchValue
        }
        getCar(params).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.Pagination.Total = res.data.count
          }
        })
      },
      openModel(type) {
        const dataList = rules();
        this.formRuleList = dataList;
        this.dialogWidth = '60%'
        this.operationType = type
        if (type == 'add') {
          this.shopTitle = '添加'
        }
        this.shopDialogVisible = true
      },
      // 弹窗表单添加
      handleAdd() {
        let flag = this.$refs['childRules'].validateForm();
        if (flag) {
          this.carLoading = true
          if (this.operationType == 'add') {
            addCar({
              provCarInfo: this.ruleForm
            }).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.carLoading = false
              this.shopDialogVisible = false
            })
          } else if (this.operationType == 'edit') {
            putCar({
              id: this.enterpriseId,
              provCarInfo: this.ruleForm
            }).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.carLoading = false
              this.shopDialogVisible = false
            })
          } else if (this.operationType == 'binding') {
            bindTruckUser({
              userId: this.ruleForm.userId,
              carNo: this.carNo,
            }).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.carLoading = false
              this.shopDialogVisible = false
            })
          }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      // 删除
      deleteItem(id) {
        this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delCar({
            id: id,
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.getList()
            }
          })
        }).catch(() => {});
      },
      // 表格操作按钮
      buttonData(row, type) {
        // console.log(row, type, 998)
        this.enterpriseId = row.id
        this.operationType = type
        if (type == 'edit') {
          const dataList = rules();
          this.formRuleList = dataList;
          this.dialogWidth = '60%'
          this.shopTitle = '编辑'
          this.ruleForm = JSON.parse(JSON.stringify(row.provCarInfo))
          this.shopDialogVisible = true
        } else if (type == 'del') {
          this.deleteItem(row.id)
        } else if (type == 'binding') {
          this.limitNo = true
          this.staffName = ''
          this.page = 1
          this.carNo = row.carNo
          this.getUserList()
          this.dialogWidth = '40%'
          const dataList = vehicle();
          this.formRuleList = dataList;
          this.shopTitle = '车辆绑定司机信息'
          this.shopDialogVisible = true
          if(row.truckUserCarInfo.user.provUserId){
            this.ruleForm.userId = row.truckUserCarInfo.user.provUserId
          }
        }
      },
      // 获取用户列表
      getUserList() {
        var params = {
          page: this.page,
          pageSize: 10,
          name: this.staffName,
          userType: 4,
        }
        getUser(params).then(res => {
          if (res.code == 200) {
            let arr = res.data.list
            let arrList = []
            arr.forEach(item1 => {
              var arrData = {
                label: null,
                value: null,
              }
              arrData.label = item1.nickName
              arrData.value = item1.provUserId
              arrList.push(arrData)
            })
            if (this.limitNo == true) {
              this.formRuleList.forEach(item => {
                if (item.type == 'searchSelect') {
                  item.options = item.options.concat(arrList);
                  let some = [];
                  item.options.forEach(el => {
                    if (!some.some(e => e.value == el.value)) {
                      some.push(el)
                    }
                  })
                  item.options = some
                  this.$forceUpdate()
                }
              })
            }
            if (arrList.length >= 10) {
              this.page = ++this.page;
            } else {
              // 已经没数据了 不需要增加数据
              this.limitNo = false;
            }
          }
        })
      },
      // 触底事件
      handleScroll() {
        if (this.limitNo) {
          this.getUserList()
        }
      },
      // 重置选择员工
      resetSelect() {
        this.formRuleList.forEach(item => {
          if (item.type == 'searchSelect') {
            item.options = []
          }
        })
        this.page = 1
        this.limitNo = true
        this.staffName = ''
      },
      // 搜索
      remoteMethod(value) {
        this.resetSelect()
        this.staffName = value
        this.getUserList()
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      closeDialog() {
        this.ruleForm = {}
        this.$refs.childRules.resetCheck();
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
