<template>
<div>
  <basic-container>
    <avue-crud
        ref="crud"
        :data="dataList"
        :option="option"
        v-model="form"
        :table-loading="loading"
        :page.sync="page"
        @on-load="onLoad"
        @row-del="rowDel"
        @search-change="searchChange"
        @row-update="rowUpdate"
        :before-open="beforeOpen"
        @search-criteria-switch="searchCriteriaSwitch"
        @row-save="rowSave">
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-upload2"
                   @click="handleImport">导入
        </el-button>
      </template>
      <template slot="urlForm" slot-scope="{ row }">
        <el-input
            placeholder="文件地址"
            size="small"
            v-if="row.$cellEdit"
            v-model="row.url"
            class="input-with-select">
          <el-button size="small" type="primary" slot="prepend" @click="download(row)">查看</el-button>
          <el-upload
              class="upload-demo"
              :show-file-list="false"
              slot="append"
              :action="action"
              :headers="headers"
              :on-success="(response)=>{onSuccessTwo(response,row)}"
              :multiple="false">
            <el-button size="small" type="primary">上传</el-button>
          </el-upload>
        </el-input>
        <span v-else>{{ row.url }}</span>
      </template>
      <template slot-scope="scope" slot="fleetIdForm">
        <crop-select corpType="CD" v-model="form.fleetId"/>
      </template>
      <template slot-scope="scope" slot="fleetIdSearch">
        <crop-select corpType="CD" v-model="form.fleetId"/>
      </template>
      <template slot-scope="scope" slot="fleetId">
        <span>{{scope.row.fleetName}}</span>
      </template>
      <template slot-scope="{type,size,row}" slot="menu">
        <el-button icon="el-icon-check" :size="size" :type="type" @click="creatingUsers(row)">创建用户</el-button>
      </template>
    </avue-crud>
    <el-dialog
        title="创建用户"
        :visible.sync="dialogVisible"
        append-to-body
        width="60%">
      <avue-form ref="formData" v-model="formData" :option="optionData">

      </avue-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="confirmSynchronization">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog title="导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
      <p style="text-align: center;color: #DC0505">
        温馨提示 第一次导入时请先下载模板
      </p>
    </el-dialog>
  </basic-container>
</div>
</template>

<script>
import {getToken} from "@/util/auth";
import {
  saveDelegationList,
  removeDelegationList,
  selectInvoiceList,
  detailDelegationList, removeFile,driverUser
} from "@/api/landTransportation/driver";
import website from "@/config/website";
import {getRoleTree} from "@/api/system/role";
import {getDeptTree} from "@/api/system/dept";
import {getPostList} from "@/api/system/post";
export default {
  name: "index",
  data(){
    return{
      form:{},
      formRow:{},
      dataList:[],
      formData:{},
      optionData:{
        span:8,
        menuBtn:false,
        column:[{
          label: "所属角色",
          prop: "roleId",
          multiple: true,
          type: "tree",
          dicData: [],
          props: {
            label: "title"
          },
          checkStrictly: true,
          slot: true,
          rules: [{
            required: true,
            message: "请选择所属角色",
            trigger: "click"
          }]
        },{
          label: "所属部门",
          prop: "deptId",
          type: "tree",
          multiple: true,
          dicData: [],
          props: {
            label: "title"
          },
          checkStrictly: true,
          slot: true,
          rules: [{
            required: true,
            message: "请选择所属部门",
            trigger: "click"
          }]
        },
          {
            label: "所属岗位",
            prop: "postId",
            type: "tree",
            multiple: true,
            dicData: [],
            props: {
              label: "postName",
              value: "id"
            },
            rules: [{
              required: true,
              message: "请选择所属岗位",
              trigger: "click"
            }],
          }]
      },
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          // {
          //   label: "数据覆盖",
          //   prop: "isCovered",
          //   type: "switch",
          //   align: "center",
          //   width: 80,
          //   dicData: [
          //     {
          //       label: "否",
          //       value: 0
          //     },
          //     {
          //       label: "是",
          //       value: 1
          //     }
          //   ],
          //   value: 0,
          //   slot: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请选择是否覆盖",
          //       trigger: "blur"
          //     }
          //   ]
          // },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },{
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/blade-client/land-driver/import-data"
          }
        ]
      },
      excelForm:{},
      dialogVisible:false,
      loading:false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        pageSizes: [10,50,100,200,300]
      },
      excelBox:false,
      action: "/api/blade-resource/oss/endpoint/put-file",
      headers: { "Blade-Auth": "Bearer " + getToken() },
      option:{
        align:'center',
        dialogWidth:'85%',
        index: true,
        searchIcon: true,
        searchIndex: 2,
        searchLabelWidth:100,
        searchSpan:8,
        column:[{
          label: '司机姓名',
          prop: 'name',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
        },{
          label: '身份证号',
          prop: 'idCard',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
        },{
          label: '准驾车型',
          prop: 'permitModel',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
        },{
          label: '电话',
          prop: 'tel',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        },{
          label: '所属车队',
          prop: 'fleetId',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
        },{
          label: '性别',
          prop: 'sex',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
          type: 'select',
          dicUrl: "/api/blade-system/dict/dictionary?code=sex",
          props: {
            label: "dictValue",
            value: "dictKey"
          },
          dataType: "number",
        },{
          label: '驾驶证有效期',
          prop: 'driveExpire',
          type: "date",
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
        },{
          label: '资格证证件号',
          prop: 'qualifiedNo',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
        },{
          label: '资格证有效期',
          prop: 'qualifiedExpire',
          type: "date",
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
        },{
          label: '押运证证件号',
          prop: 'escortNo',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
        },{
          label: '押运证有效期',
          prop: 'escortExpire',
          type: "date",
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          index: 1,
          width: 140,
          span: 8,
          cell: true,
          overHidden: true,
          search:true,
        }, {
          label: '信用等级',
          width: 150,
          span: 8,
          prop: 'salesman',
          search: true,
          overHidden: true,
          type: "select",
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=credit_rating",
          props: {
            label: "dictValue",
            value: "dictKey"
          },
        },{
          label: '附件',
          prop: 'fileList',
          type: 'dynamic',
          span:24,
          hide:true,
          showColumn:false,
          children: {
            align: 'center',
            headerAlign: 'center',
            rowAdd:(done)=>{
              // this.$message.success('新增回调');
              done()
            },
            rowDel:(row,done)=>{
              if (row.id) {
                removeFile(row.id).then(res=>{
                  done();
                })
              }else {
                done();
              }
            },
            column: [{
              width: 360,
              label: '文件地址',
              prop: "url"
            }, {
              width: 200,
              label: '文件名称',
              prop: "fileName",
              formslot: true
            },{
              width: 200,
              label: '文件属性',
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=file_type",
              props: {
                label: "dictValue",
                value: "dictValue"
              }
            }, {
              label: '备注',
              prop: "remarks",
            }]
          }
        }]
      }
    }
  },
  created() {
    let i = 0;
    this.option.column.forEach(item => {
      if (item.search) i++
    })
    this.initData(JSON.parse(localStorage.getItem("saber-userInfo")).content.tenant_id)
    if (i % 3 !== 0){
      const num = 3 - Number(i % 3)
      this.option.searchMenuSpan = num * 8;
      this.option.searchMenuPosition = "right";
    }
  },
  methods:{
    handleImport() {
      this.excelBox = true;
    },
    uploadAfter(res, done, loading, column) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    refreshChange() {
      this.onLoad(this.page, {});
    },
    handleTemplate() {
      window.open(`/api/blade-client/land-driver/import-template?${this.website.tokenHeader}=${getToken()}`);
    },
    //确认创建用户
    confirmSynchronization(){
      this.$refs['formData'].validate((valid, done) => {
        done()
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.formData))
          data.deptId = data.deptId.join(",");
          data.roleId = data.roleId.join(",");
          data.postId = data.postId.join(",");
          driverUser({
            ...data,
            id:this.formRow.id
          }).then(res=>{
            this.dialogVisible = false
            this.$message.success('创建用户成功,默认帐号：司机名称。默认密码：123456');
          })
        } else {
          return false;
        }
      });
    },
    creatingUsers(row){
      console.log(row)
      if (row.tel){
        this.dialogVisible = true
        this.formData = {}
        this.formRow = row
      }else {
        this.$message.error('请输入手机号');
      }
    },
    initData(tenantId) {
      getRoleTree(tenantId).then(res => {
        const column = this.findObject(this.optionData.column, "roleId");
        column.dicData = res.data.data;
      });
      getDeptTree(tenantId).then(res => {
        const column = this.findObject(this.optionData.column, "deptId");
        column.dicData = res.data.data;
      });
      getPostList(tenantId).then(res => {
        const column = this.findObject(this.optionData.column, "postId");
        column.dicData = res.data.data;
      });
    },
    // 获得高度
    searchCriteriaSwitch(type){
      if (type){
        this.option.height = this.option.height - 138
      }else {
        this.option.height = this.option.height + 138
      }
      this.$refs.crud.getTableHeight()
    },
    //附件上传成功
    onSuccessTwo(response,row){
      row.url = response.data.link
      row.fileName = response.data.originalName
    },
    //下载附件
    download(row){
      if (row.url){
        window.open(row.url)
      }else {
        this.$message.warning('无附件，请上传附件后再查看');
      }
    },
    //新增
    rowSave(row,done,loading){
      console.log(row)
      saveDelegationList(row).then(res=>{
        this.$message.success('保存成功');
        this.onLoad(this.page)
        done()
      }, error => {
        window.console.log(error);
        loading();
      })
    },
    //点击行编辑时查看
    beforeOpen(done,type){
      if (this.form.id){
        detailDelegationList(this.form.id).then(res=>{
          this.form = res.data.data
          done()
        })
      }else {
        done()
      }
    },
    //修改
    rowUpdate(row,index,done,loading){
      saveDelegationList(row).then(res=>{
        this.$message.success('保存成功');
        this.onLoad(this.page)
        loading();
        // done()
      }, error => {
        window.console.log(error);
        loading();
      })
    },
    //检索
    onLoad(page, params) {
      let queryParams = {
        size: page.pageSize,
        current: page.currentPage,
        ...params
      }
      this.loading = true;
      selectInvoiceList(queryParams).then(res => {
        this.dataList = res.data.data.records
        this.page.total = res.data.data.total
        this.option.height = window.innerHeight - 240;
      }).finally(() => {
        this.loading = false;
      })
    },
    //搜索
    searchChange(params,done) {
      this.onLoad(this.page,params)
      done();
    },
    //列表删除
    rowDel(row){
      this.$confirm('此操作将永久删除该单据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeDelegationList({ids:row.id}).then(res=>{
          this.$message.success('删除成功');
          this.onLoad(this.page)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
  }
}
</script>

<style scoped>

</style>
