<template>
    <d2-container>
        <div class="d2-table-view-full" style="overflow: hidden;">
            <div class="d2-table-view-header">
                <el-form label-width="100px" labelPosition="right" size="small" :inline="true" :model="filter" @keyup.enter.native="handleList" class="demo-form-inline">
                    <el-form-item label="人员编号">
                        <el-input style="width: 192px" v-model.trim="filter.userNo" placeholder="人员编号" clearable/>
                    </el-form-item>
                    <el-form-item label="停车卡类型" prop="paramCode">
                        <custom-select :value="filter.paramCode" v-model="filter.paramCode" typeName="停车卡类型" style="width: 100%"></custom-select>
                    </el-form-item>
                    <el-form-item label="名单类别" prop="useState">
                        <el-select v-model="filter.useState" placeholder="请选择" clearable>
                            <el-option  label="黑名单" value="黑名单"></el-option>
                            <el-option  label="白名单" value="白名单"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button   type="primary" @click="handleList('1')">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="d2-table-view-content">
                <div class="d2-table-view-handle">
                    <el-button @click="onCreateClick" size="small" icon="el-icon-plus">新增</el-button>
                    <el-button size="small" @click="onMutilDelClick">批量删除</el-button>
                </div>
                <d2-crud
                        title="车辆登记授权"
                        ref="d2Crud"
                        :options="tableOptions"
                        :loading="loading"
                        :columns="columns"
                        :data="data"
                        :rowHandle="rowHandle"
                        @edit="handleRowEdit"
                        @delete="handleRowRemove"
                        selection-row
                        @selection-change="handleSelectionChange"
                >
                </d2-crud>
            </div>
            <div class="d2-table-view-footer">
                <el-pagination
                        @current-change="handleCurrentChange"
                        @size-change="handleSizeChange"
                        :page-size="tableOptions.pageList[0]"
                        :page-sizes="tableOptions.pageList"
                        :current-page.sync="currentPage"
                        layout="total,sizes, prev, pager, next,jumper"
                        :total="pagination.total"
                ></el-pagination>
            </div>
        </div>
        <el-dialog
                :title="diaLogName"
                :visible.sync="operVisible"
                @close="clearForm"
                width="46%"
                :close-on-click-modal="false"
        >
            <el-form ref="form" :model="form" label-width="80px" labelPosition="right" :rules="rules">
                <el-row :gutter="15">
                    <el-col :span="12">
                    <el-form-item label="车牌号码" prop="vehicleNo">
                        <el-input maxlength="15"  v-model.trim="form.vehicleNo"/>
                    </el-form-item>
                </el-col>
                    <el-col :span="12">
                        <el-form-item label="名单类型" prop="useState">
                            <el-select v-model="form.useState" placeholder="请选择" style="width: 100%">
                                <el-option  label="黑名单" value="黑名单"></el-option>
                                <el-option  label="白名单" value="白名单"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="人员工号" prop="userNo">
                            <el-input disabled v-model.trim="form.userNo"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="人员姓名" prop="personId">
                            <registerstaff-tree ref="saffTree" :depType="type" :strr="form.userNm" v-model="personId"></registerstaff-tree>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label=部门 prop="depNm">
                            <el-input v-model.trim="form.depNm" disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="停车卡号" prop="cardId">
                            <el-input maxlength="32" v-model.trim="form.cardId"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="停车区域" prop="areaId" >
                            <el-select v-model="form.areaId" placeholder="请选择" style="width: 100%">
                                <el-option
                                        v-for="item in options"
                                        :key="item.areaId"
                                        :label="item.areaNm"
                                        :value="item.areaId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!--<el-col :span="12">-->
                        <!--<el-form-item label="车位" prop="veStall">-->
                            <!--<el-input maxlength="10" v-model.trim="form.veStall"/>-->
                        <!--</el-form-item>-->
                    <!--</el-col>-->
                    <el-col :span="24">
                        <el-form-item label="车场日期">
                            <el-date-picker
                                    v-model="time"
                                    type="datetimerange"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    :default-time="['00:00:00', '23:59:59']"
                                    @change="dateChange"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="车牌颜色" prop="vehicleColor">
                            <el-select v-model="form.vehicleColor" placeholder="请选择" style="width: 100%">
                                <el-option v-for="(item,index) in colorList" :key="index" :label="item.value" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="车辆类别" prop="carTypId">
                            <el-select v-model="form.carTypId" placeholder="请选择">
                                <el-option
                                        v-for="item in options1"
                                        :key="item.carTypId"
                                        :label="item.carTypNm"
                                        :value="item.carTypId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="车辆型号" prop="carTyp">
                            <el-input maxlength="12" v-model.trim="form.carTyp"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="车辆颜色" prop="carColor">
                            <custom-select :value="form.carColor" v-model="form.carColor" typeName="车辆颜色" style="width: 100%"></custom-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="交纳金额" prop="foregifts">
                            <el-input  v-model.trim="form.foregifts"/>
                        </el-form-item>
                    </el-col>
                    <!--<el-col :span="12">-->
                        <!--<el-form-item label="车辆类型" prop="carTypId">-->
                            <!--<custom-select :value="form.carTypId" v-model="form.carTypId" typeName="车辆类别类型" style="width: 100%"></custom-select>-->
                        <!--</el-form-item>-->
                    <!--</el-col>-->
                    <el-col :span="24">
                        <el-form-item label="车辆照片" prop="carPhotos">
                            <img v-if="form.carPhotos" :src="form.carPhotos" class="avatar">
                            <label for="upload-input">
                            <span class="buttonBox">选择</span>
                        </label>
                            <input
                                id="upload-input"
                                style="display: none"
                                type="file"
                                multiple
                                ref="upload"
                                name="img"
                                @change="upload($event)"
                        >
               <span class="buttonBox" @click="removeClick">清除</span>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                 <el-button :loading="staLoading" @click="operInstance(1)" v-if="isShow">继续添加</el-button>
        <zl-button :loading="staLoading" @click="operInstance(2)">完成</zl-button>
      </span>
        </el-dialog>
    </d2-container>
</template>
<script>
  import { tableOptions } from '../../../../assets/options'
  import {getAreaOptions} from '@/api/parking/costRules'
  import {getUserRightsList,getMessageById,uploadImg,saveOrUpdateUserRights,getCarCateOptions,getRightsListById,onDeleteRights} from '@/api/parking/mangeCar/userRights'
  export default {
    name: 'cateUser',
    components: {

    },
    data () {
      let checkNumber = (rule, value, callback) => {
        if(!value&&value!==0){
          return callback(new Error('不能为空'))
        }
        let reg = /^[0-9]*$/
        if (!reg.test(value)) {
          return callback(new Error('请输入数字'))
        } else {
          callback ()
        }
      }
      let checkCardId = (rule, value, callback) => {
        if(!value){
          return callback(new Error('不能为空'))
        }
        let reg = /^[0-9a-zA-Z]+$/
        if (!reg.test(value)) {
          return callback(new Error('请输入数字或英文'))
        } else {
          callback ()
        }
      }
      return {
        veIds:[],
        veIdss:"",
        isShow:true,
        personId:"",
        type:'teacher',
        schannelIds:[],
        schannelIdss:"",
        equipmentOptions:[],
        workStationOptions:[],
        options:[],
        options1:[],
        time:"",
        stationId:[],
        stationIds:"",
        isCreate:false,
        userId:"",
        colorList:[
          {value:"蓝色"},
          {value:"黄色"},
          {value:"黑色"},
          {value:"白色"},
          {value:"绿色"},
        ],
        staLoading: false,
        multipleSelection:[],
        func: {
          add: false,
          delete: false,
          update: false,
          select: false
        },
        falg: true,
        isExpend: true,
        tableOptions,
        loading: false,
        operVisible: false,
        diaLogName: '新增',
        lanuchs: [],
        form: {
          orgId:"",
          personId:"",
          depNm:"",
      userNm:"",
          userId:"",
          vehicleNo:"",
          useState:"",
          userNo:"",
          veName:"",
          depId:"",
          cardId:"",
          areaId:"",
          // veStall:"",
          bgTm:"",
          endTm:"",
          vehicleColor:"",
          // veParkTyp:"",
          carTyp:"",
          carColor:"",
          foregifts:'',
          carTypId:"",
          carPhotos:""
        },
        filter: {
          pageSize: 10,
          pageNum: 1,
          userNo:"",
          paramCode:"",
          useState:""
        },
        pagination: {
          total: 0
        },
        currentPage: 1,
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        columns: [
          {
            title: '人员编号',
            key: 'userNo',
            minWidth: '120',
            showOverflowTooltip: true
          },
          {
            title: '人员姓名',
            key: 'userNm',
            minWidth: '140',
            showOverflowTooltip: true
          },
          {
            title: '部门名称',
            key: 'depNm',
            minWidth: '90',
            showOverflowTooltip: true
          },
          {
            title: '车牌号码',
            key: 'vehicleNo',
            minWidth: '120',
            showOverflowTooltip: true
          },
          {
            title: '车辆型号',
            key: 'carTyp',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            title: '车辆颜色',
            key: 'paramData',
            minWidth: '90',
            showOverflowTooltip: true
          },
          {
            title: '名单类型',
            key: 'useState',
            minWidth: '90',
            // formatter (row, column, cellValue, index) {
            //   if (cellValue === "0") {
            //     return '否'
            //   }else if(cellValue === "1"){
            //     return '是'
            //   }
            // }
          },
          // {
          //   title: '车辆类别',
          //   key: 'carTypNm',
          //   minWidth: '90',
          //   showOverflowTooltip: true
          // },
          {
            title: '车辆类别',
            key: 'carTypNm',
            minWidth: '120',
            showOverflowTooltip: true
          },
          {
            title: '停车卡类型',
            key: 'carStopTyp',
            minWidth: '120',
            showOverflowTooltip: true
          },
          {
            title: '有效开始时间',
            key: 'bgTm',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            title: '有效结束时间',
            key: 'endTm',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            title: '车牌颜色',
            key: 'vehicleColor',
            minWidth: '90',
            showOverflowTooltip: true
          },
          // {
          //   title: '车位',
          //   key: 'veStall',
          //   minWidth: '90',
          //   showOverflowTooltip: true
          // },
          // {
          //   title: '车辆图片',
          //   key: 'carPhotos',
          //   minWidth: '150',
          //   showOverflowTooltip: true
          // },
          {
            title: '交纳金额',
            key: 'foregifts',
            minWidth: '90',
            showOverflowTooltip: true
          },
          {
            title: '储值余额',
            key: 'accountMoney',
            minWidth: '90',
            showOverflowTooltip: true
          },
          {
            title: '卡号',
            key: 'cardId',
            minWidth: '150',
            showOverflowTooltip: true
          },
          {
            title: '区域编号',
            key: 'areaId',
            minWidth: '120',
            showOverflowTooltip: true
          },
          {
            title: '区域',
            key: 'areaNm',
            minWidth: '120',
            showOverflowTooltip: true
          },
        ],
        rowHandle: {
          columnHeader: '操作',
          minWidth: '180',
          align: 'center',
          custom: [
            {
              text: '编辑',
              type: 'primary',
              size: 'small',
              emit: 'edit'
            },
            {
              text: '删除',
              type: 'danger',
              size: 'small',
              emit: 'delete'
            }
          ]
        },
        data: [],
        rules: {
          vehicleNo:[{required: true, message: '车牌号码不能为空', trigger: 'blur'}],
          useState:[{required: true, message: '请选择名单类型', trigger: 'blur'}],
          cardId:[{validator: checkCardId,required: true,trigger: 'blur'}],
          areaId:[{required: true, message: '请选择停车区域', trigger: 'blur'}],
          vehicleColor:[{required: true, message: '请选择车牌颜色', trigger: 'blur'}],
          carTyp:[{required: true, message: '车辆型号不能为空', trigger: 'blur'}],
          carColor:[{required: true, message: '请选择车辆颜色', trigger: 'blur'}],
          foregifts:[{validator: checkNumber,required: true, trigger: 'blur'}],
          carPhotos:[{required: true, message: '请选择图片', trigger: 'blur'}],
          carTypId:[{required: true, message: '请选择车辆类别', trigger: 'blur'}],
        }
      }
    },
watch:{
  personId:function (val) {
    this.form.personId=val
    getMessageById({userId:val}).then((res)=>{
      // if(res.dataSts==="1"){
      //   this.$message({
      //     message: '当前用户未办卡',
      //     type: 'warning'
      //   })
      //   this.$set(this.form,'userNo',"")
      //   this.$set(this.form,'depNm',"")
      //   this.$set(this.form,'userNm',"")
      //   return
      // }
this.form.userId=res.parkUserVO.userId
      this.form.orgId=res.parkUserVO.orgId
      this.$set(this.form,'userNo',res.parkUserVO.userNo)
      this.$set(this.form,'depNm',res.parkUserVO.depNm)
      this.$set(this.form,'userNm',res.parkUserVO.userNm)
      this.form.orgCode=res.parkUserVO.orgCode
      this.form.depId=res.parkUserVO.depId
    })
  }
},
    methods: {
      removeClick(){
        this.form.carPhotos=""
      },
      upload(e) {
        this.files = [];
        let files = e.target.files;
        let formData = new FormData();
        for (let k in files) {
          if (files.hasOwnProperty(k)) {
            formData.append("file", files[k]);
          }
        }
        uploadImg(formData).then(res => {
          this.$message({
            message: "上传成功",
            type: "success"
          });
          this.form.carPhotos = res;
        });

        this.$refs.upload.value = null;
      },
      dateChange (val) {
        if(val == null){
          this.form.bgTm = ''
          this.form.endTm = ''
        }else{
          this.form.bgTm = val[0]
          this.form.endTm = val[1]
        }
      },
      onCreateClick(){
        this.operVisible=true
      },
      handleTreeNode () {
        this.handleList()
      },
      handleList (val) {
        if (val) {
          this.filter.pageNum = 1
          this.currentPage = 1
        }
        this.loading = true
        getUserRightsList(this.filter)
          .then(res => {
            this.loading = false
            this.data = res.page.list
            this.pagination.total = res.page.total
          })
          .catch(err => {
            this.loading = false
          })
      },
      handleSelectionChange(val) {
        this.isCreate=false
        this.multipleSelection = val;
      },
      handleCurrentChange (val) {
        this.filter.pageNum = val
        this.handleList()
      },
      handleSizeChange (val) {
        this.filter.pageNum = 1
        this.filter.pageSize = val
        this.handleList()
      },
      operInstance (val) {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if(!this.form.userNm){
              this.$message({
                message: '请重新选择人员姓名',
                type: 'warning'
              })
              return
            }
            this.staLoading = true
            saveOrUpdateUserRights(this.form).then(res => {
              this.staLoading = false
              this.clearForm()
              if (val == 2) {
                this.operVisible = false
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.handleTreeNode()
              } else {
                this.clearForm()
              }

            }).catch(err => {
              this.staLoading = false
            })
          }
        })
      },
      handleRowEdit ({index, row}) {
        this.isShow=false
        this.diaLogName = '修改'
        getRightsListById({veId:row.veId}).then(res => {
          this.form = res.parkVehicle
     this.time=res.value
          // this.personId=res.parkVehicle
        })
        this.operVisible = true
      },
      onMutilDelClick(){
        this.veIds=[]
        if(!this.multipleSelection.length){
          this.$message({
            message: '请选择记录',
            type: 'warning'
          })
        }else{
          this.$confirm(`确定删除当前车辆授权?`, '确认操作', {
            confirmButtonText: '确定',
            cancelButtonText: '放弃',
            type: 'warning'
          }).then(() => {
            this.multipleSelection.forEach((item,index)=>{
              this.veIds.push(item.veId)
            })
            this.veIdss=this.veIds.join(",")
            onDeleteRights({veIds:this.veIdss}).then(res=>{
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.handleTreeNode()
            })
          })
        }
      },
      handleRowRemove ({index, row}) {
        this.$confirm(`确定删除当前车辆授权?`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '放弃',
          type: 'warning'
        }).then(() => {
          onDeleteRights({veIds:row.veId}).then(res=>{
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.handleTreeNode()
          })
        })
      },
      clearForm () {
        // console.log(333)
        if (this.$refs['form']!==undefined) {
          this.$refs['form'].resetFields()
        }
        this.form = {}
        this.$nextTick(()=>{
          this.$refs.saffTree.cleanName()
        })
        this.diaLogName = '新增'
        this.time=""
        this.isShow=true
      },
    },
    mounted () {
      // this.clearForm()
      getAreaOptions().then((res)=>{
        this.options=res.list
      })
      getCarCateOptions().then(res=>{
        this.options1=res.list
      })
      // getEquipmentOptions().then(res=>{
      //   this.equipmentOptions=res.idNm
      // })
      this.filter.pageSize = this.tableOptions.pageList[0]
      this.tableOptions = this.$calcTableHeight(tableOptions, 102)
      this.handleTreeNode()
    }
  }
</script>
<style>
    .buttonBox{
        display: inline-block;
        width: 40px;
        height: 30px;
        line-height: 30px;
        border: 1px solid #ccc;
        text-align: center;
        margin-right: 10px;
    }
    .d2-table-view-full{
        height: 100%;
    }
    .timeBox{
        margin-top: 10px;
    }
    .timePay{
        margin-left: 8px;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
    .timeLabel label{
        width: 110px !important;
    }
    .bankLabel label{
        font-size: 13px;
    }
    .el-form-item__label {
        text-align: left !important;
    }
    .d2-table-view{
        overflow: hidden;
    }
    .d2-table-view-content{
        height: 100%;
    }
    .el-table{
        height: 450px !important;
    }
</style>