<template>
  <div class="mod-config">
    <el-form label-position="top" style="margin-top: 1px; margin-left: 0px;">
      <el-form :inline="true" label-position="top" style="margin-top: 0px">
        <el-button type="primary" @click="searchTable()">查询</el-button>
        <el-button type="primary" @click="addModal()">新增</el-button>
        <download-excel
          :fields="fields()"
          :data="exportData"
          type="xls"
          :name="exportName"
          :header="exportHeader"
          :footer="exportFooter"
          :fetch="createExportData"
          :before-generate="startDownload"
          :before-finish="finishDownload"
          worksheet="导出信息"
          class="el-button el-button--primary el-button--medium">
          {{ '导出' }}
        </download-excel>
      </el-form>
    </el-form>
    <el-table
      :data="dataList"
      :height="height"
      border
      v-loading="dataListLoading"
      style="width: 100%; ">
      <el-table-column
        v-for="(item,index) in columnList1" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden"> {{ scope.row[item.columnProp] }}</span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]"
                                             style="width: 100px; height: 80px"/></span>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="150"
        fixed="right"
        label="操作">
        <template slot-scope="scope">
          <a type="text" size="small" @click="accessModel(scope.row)">授权</a>
          <a type="text" size="small" @click="updateModel(scope.row)">修改</a>
          <a type="text" size="small" @click="deleteData(scope.row)">删除</a>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      width="460px"
      :title="!dataForm.id ?  '添加' :'编辑'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form  label-position="top" label-width="100px" :rules="dataRole">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="'BU编码'" prop="buNo" :rules="dataRole.buNo">
              <el-input v-model="dataForm.buNo" :disabled="this.dataForm.id!=0"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="'BU名称'" prop="buDesc" :rules="dataRole.buDesc">
              <el-input v-model="dataForm.buDesc"  ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="在用">
              <el-select filterable v-model="dataForm.active" >
                <el-option label="Y" value="Y"></el-option>
                <el-option label="N" value="N"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item :label="'备注'">
              <el-input v-model="dataForm.remark" style="" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveData()">{{'确定'}}</el-button>
        <el-button type="primary" @click="visible = false">{{'关闭'}}</el-button>
      </span>
    </el-dialog>
      <el-dialog
        style="font-size: 12px"
        v-drag
        :title="'BU授权'"
        :visible.sync="accessModelFlag"
        width="518px"
        :append-to-body="true">
      <el-transfer v-model="accessBuList"  class="rq" filterable :props="{
      key: 'username',
      label: 'userDisplay'
    }" :data="userList" :titles="['未选择', '已选择']"></el-transfer>
      <span slot="footer" class="dialog-footer">
        <div style="margin-top: 5px">
                <el-button type="primary" @click="saveAccessBuListForBu()">确定</el-button>
                <el-button @click="accessModelFlag = false" type="primary">取消</el-button>
        </div>
    </span>
    </el-dialog>
    <Chooselist ref="baseList"  @getBaseData="getBaseData"></Chooselist>
  </div>
</template>

<script>
  import {
    getBUList,
    saveBU,
    deleteBU,
    searchAccessBuListForUser,
    saveAccessBuListForBu,
  } from "@/api/base/site.js"
  import Chooselist from '@/views/modules/common/Chooselist'
  export default {
    components: {
      Chooselist
    },
    data() {
      return {
        rowBuNo:'',
        accessModelFlag:false,
        userList:[],
        accessBuList:[],
        dataList: [],
        height:200,
        searchData: {
          site:this.$store.state.user.site,
          username: this.$store.state.user.name,
        },
        visible:false,
        dataListLoading: false,
        currentRow:'',
        columnList1:[
          {
            userId: this.$store.state.user.name,
            functionId: 100001003,
            serialNumber: '100001003Table1BuNo',
            tableId: "100001003Table1",
            tableName: "BU列表",
            columnProp: "buNo",
            headerAlign: "center",
            align: "left",
            columnLabel: "BU编码",
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 80
          },{
            userId: this.$store.state.user.name,
            functionId: 100001003,
            serialNumber: '100001003Table1BuDesc',
            tableId: "100001003Table1",
            tableName: "BU列表",
            columnProp: "buDesc",
            headerAlign: "center",
            align: "left",
            columnLabel: "BU名称",
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120
          },{
            userId: this.$store.state.user.name,
            functionId: 100001003,
            serialNumber: '100001003Table1Active',
            tableId: "100001003Table1",
            tableName: "BU列表",
            columnProp: "active",
            headerAlign: "center",
            align: "left",
            columnLabel: "是否在用",
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 80
          },{
            userId: this.$store.state.user.name,
            functionId: 100001003,
            serialNumber: '100001003Table1Remark',
            tableId: "100001003Table1",
            tableName: "BU列表",
            columnProp: "remark",
            headerAlign: "center",
            align: "left",
            columnLabel: "备注",
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120
          },
        ],
        dataForm:{
          id:'',
          site: '',
          buNo:'',
          buDesc:'',
          active:'Y',
          remark:'',
          username:'',
        },
        dataRole: {
          buNo: [
            {
              required: true,
              message: ' ',
              trigger: 'change'
            }
          ],
          buDesc: [
            {
              required: true,
              message: ' ',
              trigger: 'change'
            }
          ],
        },
        // 导出 start
        exportData: [],
        exportName: 'BU清单'+this.dayjs().format('YYYYMMDDHHmmss'),
        exportHeader: ["BU清单"],
        exportFooter: [],
        // 导出 end
      }
    },

    mounted() {
      this.$nextTick(() => {
        this.height = window.innerHeight - 140;
      })
      this.searchTable()
    },
    watch: {
      dataForm: {
        deep: true,
        handler: function (newV, oldV) {
          this.dataForm.buNo = this.dataForm.buNo.toUpperCase()
        }
      },
    },
    methods: {
      // 获取基础数据列表S
      getBaseList (val, type) {
        this.tagNo = val
        this.tagNo1 = type
        this.$nextTick(() => {
          let strVal = ''
          if (val === 1013) {
            if(type==1) {
              strVal = this.dataForm.partType
            }
          }
          this.$refs.baseList.init(val, strVal)
        })
      },
      /* 列表方法的回调 */
      getBaseData (val) {
        if (this.tagNo === 1013) {
          if(this.tagNo1==1) {
            this.dataForm.partType = val.Base_id
            this.dataForm.partTypeDesc = val.Base_desc
          }
        }
      },
      searchTable(){
        getBUList(this.searchData).then(({data}) => {
          //区分请求成功和失败的状况
          if (data && data.code == 0) {
            this.dataList = data.rows;
          } else {
            this.dataList = [];
          }
        });
      },
      addModal(){
        this.dataForm={
          id:0,
          site: this.$store.state.user.site,
          buNo:'',
          buDesc:'',
          active:'Y',
          remark:'',
          username:this.$store.state.user.name,
        }
        this.visible=true;
      },
      updateModel(row){
        this.dataForm={
          id:row.id,
          site: row.site,
          buNo:row.buNo,
          buDesc:row.buDesc,
          active:row.active,
          remark:row.remark,
          username:this.$store.state.user.name,
        }
        this.visible=true;
      },
      saveData(){
        if(this.dataForm.buNo==''||this.dataForm.buNo==null){
          this.$alert('请输入BU编码！', '错误', {
            confirmButtonText: '确定'
          })
          return false;
        }
        if(this.dataForm.buDesc==''||this.dataForm.buDesc==null){
          this.$alert('请输入BU名称！', '错误', {
            confirmButtonText: '确定'
          })
          return false;
        }
        saveBU(this.dataForm).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success( '操作成功')
            this.visible = false
            this.searchTable();
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      deleteData(row){
        this.$confirm('确定要删除这条数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteBU(row).then(({data}) => {
            if (data && data.code === 0) {
              this.$message.success( '操作成功')
              this.searchTable();
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {
        })
      },
      accessModel(row){
        searchAccessBuListForUser({site:this.$store.state.user.site,
          buNo: row.buNo,
          active:'Y'}).then(({data}) => {
          this.accessBuList = data.accessBuList
          this.userList=data.userList
        })
        this.rowBuNo=row.buNo
        this.accessModelFlag=true
      },
      saveAccessBuListForBu(){
        let inList=[];
        for (let i = 0; i < this.accessBuList.length; i++) {
          let inData={
            site:this.$store.state.user.site,
            username:this.accessBuList[i],
            buNo:this.rowBuNo
          }
          inList.push(inData)
        }
        let saveData={
          site:this.$store.state.user.site,
          buNo:this.rowBuNo,
          accessBuList:inList,
        }
        saveAccessBuListForBu(saveData).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success( '操作成功')
            this.accessModelFlag = false
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      //导出excel
      async createExportData() {

        return this.dataList;
      },
      startDownload() {
        //  this.exportData = this.dataList

      },
      finishDownload() {
      },
      fields() {
        let json = "{"
        this.columnList1.forEach((item, index) => {
          if (index == this.columnList1.length - 1) {
            json += "\"" + item.columnLabel + "\"" + ":" + "\"" + item.columnProp + "\""
          } else {
            json += "\"" + item.columnLabel + "\"" + ":" + "\"" + item.columnProp + "\"" + ","
          }
        })
        json += "}"
        let s = eval("(" + json + ")")

        return s
      },
    },
  }
</script>

<style scoped>


</style>
