<template>
  <div>
    <el-breadcrumb class="heading">
      <el-breadcrumb-item :to="{ path: '/' }">平台首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/oilsupplier/basisbuild' }">基建类资质对照表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" style="height: calc(100vh - 115px);">
      <div slot="header">
        <span>
          <i class="icon icon-table2"></i> 基建类资质对照表
        </span>
        <span style="float: right;">
          <router-link :to="'/oilsupplier/basisbuild/add/operation'">
            <el-button type="primary" size="mini" style="margin-left:10px; margin-top: -4px;">添加</el-button>
          </router-link>
          <el-button type="primary" size="mini" style="margin-left:10px; margin-top: -4px;" @click="exportExcel">导出
          </el-button>
        </span>
        <el-form ref="form" :inline="true" style="float: right; margin-top: -10px">
          <el-form-item label="上报时间">
            <el-date-picker size="mini" style="width: 220px" v-model="CreateOn" type="daterange" range-separator="至"
              start-placeholder="生成日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-dropdown split-button type="primary" size="mini" @click="handleSearch" @command="searchCommand">
              查询
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="search">高级查询</el-dropdown-item>
                <el-dropdown-item command="clear">查询重置</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="entityList" id="rebateSetTable" size="mini" border height="calc(100vh - 243px)" style="width: 100%"
        @sort-change="orderby">
        <el-table-column label="操作" min-width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <router-link :to="'/oilsupplier/basisbuild/' + scope.row.Id + '/operation'">
              <el-button type="primary" plain title="编辑" size="mini">编辑</el-button>
            </router-link>
            <el-dropdown @command="MoreCmdClick">
              <el-button size="mini" type="primary" plain>
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="GetCommand('Set', scope.row)">审核部门</el-dropdown-item>
                <!--<el-dropdown-item :command="GetCommand('Delete', scope.row)">删除数据</el-dropdown-item>-->
              </el-dropdown-menu>
            </el-dropdown>
            <!--<el-popover placement="top" title="提示">-->
            <!--<el-alert-->
            <!--title=""-->
            <!--description="确认要删除吗？"-->
            <!--type="warning"-->
            <!--:closable="false">-->
            <!--</el-alert>-->
            <!--<br/>-->
            <!--<div style="text-align: right; margin: 0">-->
            <!--<el-button type="primary" size="mini" @click="deleteEntity(scope.row)">删除</el-button>-->
            <!--</div>-->
            <!--<el-button slot="reference" type="primary" plain title="删除" style="margin-left:3px" size="mini">删除</el-button>-->
            <!--</el-popover>-->
          </template>
        </el-table-column>

        <el-table-column v-for="column in tableColumns" :prop="column.prop" sortable :min-width="column.width"
          :label="column.label" :key="column.Id" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ transferStr(scope.row[column.prop]) }}
          </template>
        </el-table-column>
        <!--动态显示的表头-->
        <el-table-column v-for="column in dynamicTableColumns" :prop="column.prop" sortable :width="300"
          :key="column.Id" :label="column.label" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ transferStr(scope.row[column.prop]) }}
          </template>
        </el-table-column>
        <!--<el-table-column prop="CreateOn" sortable min-width="150" label="生成时间" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ jstimehandle(scope.row.CreateOn+'') }}
          </template>
        </el-table-column>-->
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 15, 20, 25]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
        :total="currentItemCount">
      </el-pagination>
    </el-card>

    <el-dialog title="高级查询" :visible.sync="dialogVisible" width="720px">
      <el-form ref="advancedsearchForm" label-width="110px">
        <el-row>

          <el-col :span="12">
            <el-form-item label="生成时间">
              <el-date-picker size="mini" v-model="CreateOn" type="daterange" style="width:100%" range-separator="至"
                start-placeholder="生成日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="编码">
              <el-input size="mini" v-model="searchForm.Code" style="width:100%" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="名称">
              <el-input size="mini" v-model="searchForm.Name" style="width:100%" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleSearch">查 询</el-button>
      </span>
    </el-dialog>
    <el-dialog title="设置审批部门" :visible.sync="deptsetVisible">
      <el-row>
        <el-col :span="12">
          审批步骤：
          <el-select v-model="setForm.AuditStepCode" ref="selectAuditStep" placeholder="请选择" size="small">
            <el-option v-for="item in AuditStepOptions" :key="item.Id" :label="item.Key" :value="item.Value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="12">
          审批部门：
          <el-tree style="border: 0" show-checkbox node-key="id" :data="operationOrganizeData" :props="organizeProps"
            ref="operationOriganizeTree">
          </el-tree>
        </el-col>
      </el-row>
      <div slot="footer">
        <el-button @click="deptsetVisible = false">取消</el-button>
        <el-button type="primary" @click="saveApprovalDept()">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import {
    mapGetters
  } from 'vuex'
  import api from '@/api/oilsupplier/basisbuild'
  import setapi from '@/api/oilsupplier/oilclassorgset'
  import FileSaver from "file-saver";
  import XLSX from "xlsx";

  export default {
    computed: {
      ...mapGetters({
        authUser: 'authUser'
      })
    },
    name: 'oilbasisbuild',

    data() {
      return {
        deptsetVisible: false,
        dialogVisible: false,
        // 列表数据
        entityList: [],
        // 分页参数
        size: 10,
        currentPage: 1,
        currentItemCount: 0,
        // 列表排序
        Column: {
          Order: '',
          Prop: ''
        },
        // 查询时间
        CreateOn: [],
        // 查询项
        searchFormReset: {},
        searchForm: {
          Id: '',
          Code: '',
          Name: '',
          F01: '',
          F02: '',
          F03: '',
          F04: '',
          F05: '',
          F06: '',
          F07: '',
          F08: '',
          F09: '',
          F10: '',
          F11: '',
          F12: '',
          F13: '',
          F14: '',
          F15: '',
          F16: '',
          F17: '',
          F18: '',
          F19: '',
          F20: '',
          F21: '',
          F22: '',
          F23: '',
          F24: '',
          F25: '',
          F26: '',
          F27: '',
          F28: '',
          F29: '',
          F30: '',
          F31: '',
          F32: '',
          F33: '',
          F34: '',
          F35: '',
          F36: '',
          F37: '',
          F38: '',
          F39: '',
          F40: '',
          Remark: ''

        },
        setForm: {
          SupplierTypeCode: '02',
          SupplierTypeName: '基建类',
          AuditStepCode: '',
          AuditStepName: ''
        },
        dynamicTableColumns: [],
        tableColumns: [

          {
            prop: 'Code',
            label: '编码',
            width: 100,
            sort: true
          },

          {
            prop: 'Name',
            label: '名称',
            width: 260,
            sort: true
          }
        ],
        organizeProps: {
          value: 'id',
          label: 'name',
          children: 'children'
        },
        operationOrganizeData: [],
        AuditStepOptions: []
      }
    },
    created() {
      // 查询条件初始值备份
      Object.assign(this.searchFormReset, this.searchForm)
      this.initTableHeader()
      // 查询列表
      this.initDatas()
      this.getDictOptions()
    },
    methods: {
      initTableHeader() {
        setapi.initBbTableHeader(this.$axios).then(res => {
          console.log(res)
          this.dynamicTableColumns = res.data.items
        })
      },
      saveApprovalDept() {
        let organizeids = []
        let organize = this.$refs.operationOriganizeTree.getCheckedNodes()
        organize.forEach(row => {
          organizeids.push(row.id)
        })
        this.setForm.AuditStepName = this.$refs.selectAuditStep.selectedLabel + ''
        setapi.addOrganize(this.selecteclassid, organizeids, this.setForm, this.$axios).then(res => {
          if (res.data.code === 0) {
            this.$message({
              type: 'success',
              message: res.data.message
            })
            this.deptsetVisible = false
          } else {
            this.$message({
              type: 'warning',
              message: res.data.message
            })
          }
          console.log(res.data)
        }).catch(err => {
          console.log(err)
        })
      },
      deptSet(val) {
        let stcode = this.setForm.SupplierTypeCode
        this.deptsetVisible = true
        this.selecteclassid = val.Id
        // request
        this.$axios.get('classorgsetting/getdepartment?id=' + this.selecteclassid + '&stcode=' + stcode, {})
          .then(res => {
            // response
            this.setForm.AuditStepCode = res.data.AuditStepCode
            this.operationOrganizeData = window.toolfun_gettreejson(res.data.Organize, 'id', 'pId', 'id,name,scope')
            if (!res.data.SelectedOrganize) {
              res.data.SelectedOrganize = []
            }
            this.$refs.operationOriganizeTree.setCheckedKeys(res.data.SelectedOrganize, true)
          })
          .catch(err => {
            console.log(err)
          })
      },
      MoreCmdClick(cmd) {
        if (cmd.Command === 'Set') {
          this.deptSet(cmd.row)
        } else if (cmd.Command === 'Delete') {
          this.deleteEntity(cmd.row)
        }
      },
      GetCommand(cmdType, row) {
        let cmd = {}
        cmd.Command = cmdType
        cmd.row = row
        return cmd
      },
      initDatas() {
        // 分页及列表条件
        let params = {
          _currentPage: this.currentPage,
          _size: this.size,
          Order: this.Column.Order,
          Prop: this.Column.Prop
        }
        let myCreateOn = []
        // 解析时间
        if (this.CreateOn != null && this.CreateOn.length === 2) {
          this.CreateOn[1].setHours(23)
          this.CreateOn[1].setMinutes(59)
          this.CreateOn[1].setSeconds(59)
          myCreateOn.push(this.formatDateTime(this.CreateOn[0]))
          myCreateOn.push(this.formatDateTime(this.CreateOn[1]))
        }
        // 查询条件
        Object.assign(params, this.searchForm)
        // 访问接口
        api.getList(myCreateOn.join(','), params, this.$axios).then(res => {
          this.entityList = res.data.items
          this.currentItemCount = res.data.currentItemCount
        }).catch(err => {
          console.error(err)
        })
      },

      getDictOptions() {
        api.getDictList(this.$axios).then(res => {
          // this.dictOptions.customerList = res.data.items['customerList']
          // this.dictOptions.projectList = res.data.items['projectList']
          this.AuditStepOptions = res.data.items['AuditStep']
        }).catch(err => {
          console.error(err)
        })
      },
      exportExcel() {
        /* generate workbook object from table */
        let wb = XLSX.utils.table_to_book(
          document.querySelector("#rebateSetTable")
        );
        /* get binary string as output */
        let wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          FileSaver.saveAs(
            new Blob([wbout], {
              type: "application/octet-stream"
            }),
            "BasisBuild.xlsx"
          );
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      },

      searchCommand(command) {
        if (command === 'search') {
          this.dialogVisible = true
        } else if (command === 'clear') {
          this.clearSearch()
        }
      },
      // 列表排序功能
      orderby(column) {
        if (column.order === 'ascending') {
          this.Column.Order = 'asc'
        } else if (column.order === 'descending') {
          this.Column.Order = 'desc'
        }
        this.Column.Prop = column.prop
        this.initDatas()
      },
      clearSearch() {
        Object.assign(this.searchForm, this.searchFormReset)
        // this.searchForm = this.searchFormReset;
        this.CreateOn = ''
        this.initDatas()
      },
      handleSearch() {
        this.currentPage = 1
        this.dialogVisible = false
        this.initDatas()
      },
      handleCurrentChange(value) {
        this.currentPage = value
        this.initDatas()
      },
      handleSizeChange(value) {
        this.size = value
        this.currentPage = 1
        this.initDatas()
      },
      deleteEntity(row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api.deleteEntity(row.Id, this.$axios).then(res => {
            if (res.data.code === 0) {
              this.initDatas()
              this.$message({
                type: 'success',
                message: res.data.message
              })
            } else {
              this.$message({
                type: 'warning',
                message: res.data.message
              })
            }
          }).catch(err => {
            console.error(err)
          })
        }).catch(err => {
          console.error(err)
        })
      },

      transferStr(val) {
        if (val === '1') {
          return '是'
        }
        if (val === '0') {
          return ''
        } else {
          return val
        }
      },

      jstimehandle(val) {
        if (val === '') {
          return '----'
        } else if (val === '0001-01-01T08:00:00+08:00') {
          return '----'
        } else if (val === '5000-01-01T23:59:59+08:00') {
          return '永久'
        } else {
          val = val.replace('T', ' ')
          return val.substring(0, 10)
        }
      },

      formatDateTime(date) {
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        m = m < 10 ? ('0' + m) : m
        var d = date.getDate()
        d = d < 10 ? ('0' + d) : d
        var h = date.getHours()
        var minute = date.getMinutes()
        minute = minute < 10 ? ('0' + minute) : minute
        return y + '-' + m + '-' + d + ' ' + h + ':' + minute
      }
    }
  }

</script>
