<template>
  <div class="mod-config">
    <el-form :inline="true" label-position="top" :model="searchData" @keyup.enter.native="getDataList()">
      <el-form-item :label="'部门编码'">
        <el-input v-model="searchData.departmentId" style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'部门名称'">
        <el-input v-model="searchData.departmentName" style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="' '">
        <el-button @click="getDataList()">查询</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-item>
    </el-form>

    <el-table
      :height="height"
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%;">
      <el-table-column
        v-for="(item,index) in columnList" :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
        fixed="right"
        header-align="center"
        align="center"
        width="100"
        label="操作">
        <template slot-scope="scope">
          <el-link style="cursor: pointer" @click="deleteModal(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 0px"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[20, 50, 100, 1000]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <el-dialog title="分类" :close-on-click-modal="false" v-drag :visible.sync="modalFlag" width="430px">
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item label="BU" prop="bu" :rules="rules.bu">
          <el-select v-model="modalData.bu" placeholder="请选择" :disabled="modalDisableFlag" style="width: 383px">
            <el-option
              v-for = "i in userBuList"
              :key = "i.buNo"
              :label = "i.sitename"
              :value = "i.buNo">
              <span style="float: left;width: 100px">{{ i.sitename }}</span>
              <span style="float: right; color: #8492a6;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; font-size: 11px;width: 60px">
                {{ i.buDesc }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item prop="departmentId" :rules="rules.departmentIdType">
          <span slot="label" style="" @click="getBaseList(1053)"><a herf="#">部门编码</a></span>
          <el-input v-model="modalData.departmentId" style="width: 140px"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName" :rules="rules.departmentNameType">
          <el-input v-model="modalData.departmentName" disabled style="width: 230px"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="height:40px;margin-top: 10px;text-align:center">
        <el-button type="primary" @click="saveData()">保存</el-button>
        <el-button type="primary" @click="modalFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>

    <Chooselist ref="baseList"  @getBaseData="getBaseData"></Chooselist>

  </div>
</template>

<script>
  import {getSiteAndBuByUserName} from "@/api/qc/qc.js"
  import {departmentSearch, departmentSave, departmentDelete} from "@/api/department.js"
  import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'
  import Chooselist from '@/views/modules/common/Chooselist'
  import department from './department.vue'
  export default {
    components: {Chooselist},
    watch: {
      searchData: {
        deep: true,
        handler: function (newV, oldV) {
          this.searchData.departmentId = this.searchData.departmentId.toUpperCase()
        }
      },
      modalData: {
        deep: true,
        handler: function (newV, oldV) {
          this.modalData.departmentId = this.modalData.departmentId.toUpperCase()
        }
      }
    },
    data () {
      return {
        // 是否收藏
        favorite: false,
        // 导出 start
        exportData: [],
        exportName: "设备分类" + this.dayjs().format('YYYYMMDDHHmmss'),
        exportHeader: ["设备分类"],
        exportFooter: [],
        resultList: [],
        // 导出 end
        searchData: {
          site: this.$store.state.user.site,
          username: this.$store.state.user.name,
          departmentId: '',
          departmentName: '',
          page: 1,
          limit: 10,
        },
        height: 200,
        pageIndex: 1,
        pageSize: 20,
        totalPage: 0,
        dataList: [],
        dataListLoading: false,
        dataListSelections: [],
        modalFlag: false,
        modalDisableFlag: false,
        modalData: {
          flag: '',
          bu: '',
          site: this.$store.state.user.site,
          departmentId: '',
          departmentName: '',
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
        },
        departmentList: [],
        // 展示列集
        columnList: [
          {
            columnProp: 'site',
            headerAlign: "center",
            align: "center",
            columnLabel: '工厂',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'buDesc',
            headerAlign: "center",
            align: "center",
            columnLabel: 'BU',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'departmentId',
            headerAlign: "center",
            align: "center",
            columnLabel: '部门编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'departmentName',
            headerAlign: "center",
            align: "center",
            columnLabel: '部门名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'createDate',
            headerAlign: 'center',
            align: "center",
            columnLabel: '创建时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'createBy',
            headerAlign: 'center',
            align: "center",
            columnLabel: '创建人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'updateDate',
            headerAlign: 'center',
            align: "center",
            columnLabel: '更新时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'updateBy',
            headerAlign: 'center',
            align: "center",
            columnLabel: '更新人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
        ],
        levelList: [],
        rules: {
          departmentIdType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          departmentNameType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          bu:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ]
        },
        userBuList: []
      }
    },

    mounted () {
      this.$nextTick(() => {
        this.height = window.innerHeight - 210
      })
    },

    created () {
      // 获取用户的 site 和 bu
      this.getSiteAndBuByUserName()
      // 校验用户是否收藏
      this.favoriteIsOk()
      // 获取数据列表
      this.getDataList()
    },

    methods: {
      // 获取用户的bu
      getSiteAndBuByUserName () {
        let tempData = {
          username: this.$store.state.user.name,
        }
        getSiteAndBuByUserName(tempData).then(({data}) => {
          if (data.code === 0) {
            this.userBuList = data.rows
          }
        })
      },

      getBaseData (val) {
        if (this.tagNo === 93) {
          this.modalData.site = val.SiteID
          this.$set(this.modalData,'siteName',val.SiteName);
        }
        if (this.tagNo === 1053) {
          this.modalData.departmentId = val.dept_id
          this.$set(this.modalData,'departmentName',val.dept_name);
        }
      },

      // 获取基础数据列表
      getBaseList (val) {
        this.tagNo = val
        this.$nextTick(() => {
          let strVal = "";
          if (val === 93){
            strVal = this.modalData.site
            this.$refs.baseList.init(val,strVal)
          }
          if (val === 1053) {
            strVal = this.modalData.departmentId
            this.$refs.baseList.init(val, strVal)
          }
        })
      },

      // 获取数据列表
      getDataList () {
        this.searchData.limit = this.pageSize
        this.searchData.page = this.pageIndex
        departmentSearch(this.searchData).then(({data}) => {
          if (data.code === 0) {
            this.dataList = data.page.list
            this.pageIndex = data.page.currPage
            this.pageSize = data.page.pageSize
            this.totalPage = data.page.totalCount
          }
          this.dataListLoading = false
        })
      },

      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },

      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },

      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },

      addModal () {
        this.modalData = {
          flag: '1',
          bu: this.userBuList[0].buNo,
          site: this.$store.state.user.site,
          departmentId: '',
          departmentName: '',
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
        }
        this.modalDisableFlag = false
        this.modalFlag = true
      },

      // 删除
      deleteModal (row) {
        this.$confirm(`是否删除这个部门?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          departmentDelete(row).then(({data}) => {
            if (data && data.code === 0) {
              this.getDataList()
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {}
              })
            } else {
              this.$alert(data.msg, '错误', {
                confirmButtonText: '确定'
              })
            }
          })
        }).catch(() => {
        })
      },

      // 新增
      saveData () {
        if (this.modalData.bu === '' || this.modalData.bu == null) {
          this.$message.warning('请选择BU！')
          return
        }
        if (this.modalData.departmentId === '' || this.modalData.departmentId == null) {
          this.$message.warning('请输入部门编码！')
          return
        }
        departmentSave(this.modalData).then(({data}) => {
          if (data && data.code === 0) {
            this.getDataList()
            this.modalFlag = false
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {}
            })
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      },

      // 校验用户是否收藏
      favoriteIsOk () {
        let userFavorite = {
          userId: this.$store.state.user.id,
          languageCode: this.$i18n.locale
        }
        userFavoriteList(userFavorite).then(({data}) => {
          for (let i = 0; i < data.list.length; i++) {
            if (this.$route.meta.menuId === data.list[i].menuId) {
              this.favorite = true
            }
          }
        })
      },

      // 收藏 OR 取消收藏
      favoriteFunction () {
        let userFavorite = {
          userId: this.$store.state.user.id,
          functionId: this.$route.meta.menuId,
        }
        if (this.favorite) {
          removeUserFavorite(userFavorite).then(({data}) => {
            this.$message.success(data.msg)
            this.favorite = false
          })
        } else {
          // 收藏
          saveUserFavorite(userFavorite).then(({data}) => {
            this.$message.success(data.msg)
            this.favorite = true
          })
        }
      },

      //导出excel
       async createExportData () {
        this.searchData.limit = -1
        this.searchData.page = 1
         await departmentSearch(this.searchData).then(({data}) => {
          this.resultList= data.page.list
        })
        return this.resultList
      },

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

    }
  }
</script>
