<template>
  <div class="mod-config">
    <!-- 条件查询 -->
    <el-form :inline="true" label-position="top" :model="searchData">
      <el-form-item :label="'BU'">
        <el-select v-model="searchData.buDesc" placeholder="请选择" clearable style="width: 80px">
          <el-option
            v-for = "i in userBuList"
            :key = "i.buNo"
            :label = "i.buDesc"
            :value = "i.buDesc">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="'检验等级编码'">
        <el-input v-model="searchData.samplingLevelNo" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'检验等级描述'">
        <el-input v-model="searchData.samplingLevelDesc" clearable style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item :label="'是否可用'">
        <el-select v-model="searchData.samplingLevelActive" style="width: 80px">
          <el-option label="全部" value=""></el-option>
          <el-option label="是" value="Y"></el-option>
          <el-option label="否" value="N"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="' '">
        <el-button v-if="!authSearch" type="primary" @click="getDataList()">查询</el-button>
        <el-button v-if="!authSave" type="primary" @click="addModal()">新增</el-button>
        <el-button @click="exportExcel()" type="primary" style="margin-left: 2px">{{'导出'}}</el-button>
      </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">
            <span v-if="columnsProp.includes(item.columnProp)">{{ scope.row[`${item.columnProp}Desc`] }}</span>
            <span v-else>
              {{ scope.row[item.columnProp] }}
            </span>
          </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="130"
        label="操作">
        <template slot-scope="scope">
          <el-link style="cursor: pointer" v-if="!authUpdate" @click="updateModal(scope.row)">修改</el-link>
          <el-link style="cursor: pointer" v-if="!authDelete" @click="deleteModal(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增和修改 -->
    <el-dialog title="检验方法" :close-on-click-modal="false" v-drag :visible.sync="modalFlag" width="500px">
      <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: 456px">
            <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 label="检验等级描述:" prop="samplingLevelDesc" :rules="rules.samplingLevelDescType">
          <el-input v-model="modalData.samplingLevelDesc" style="width: 221px"></el-input>
        </el-form-item>
        <el-form-item :label="'是否可用'" prop="samplingLevelActive" :rules="rules.samplingLevelActiveType">
          <el-select filterable v-model="modalData.samplingLevelActive" style="width: 221px">
            <el-option label="是" value="Y"></el-option>
            <el-option label="否" value="N"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true" label-position="top" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item label="备注说明:">
          <el-input v-model="modalData.samplingLevelRemark" style="width: 456px"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="height:35px;margin-top: 15px;text-align:center">
        <el-button type="primary" @click="saveData()">保存</el-button>
        <el-button type="primary" @click="modalFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>
  </div>
</template>

<script>
  import {
    samplingLevelSearch, // 查询检验等级
    samplingLevelSave, // 新增检验等级
    samplingLevelUpdate, // 修改检验等级
    samplingLevelDelete, // 删除检验等级
    getSiteAndBuByUserName
  } from "@/api/qc/qc.js"
  import {getTableDefaultListLanguage, getTableUserListLanguage} from "@/api/table.js"
  import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'
  import excel from "@/utils/excel-util.js"
  export default {
    data () {
      return {
        columnsProp:['createBy','samplingLevelActive','updateBy'],
        // 是否收藏
        favorite: false,
        // 导出 start
        exportData: [],
        exportName: "样本量" + this.dayjs().format('YYYYMMDDHHmmss'),
        exportHeader: ["样本量"],
        exportFooter: [],
        exportList: [],
        // 导出 end
        searchData: {
          site: '',
          userName: this.$store.state.user.name,
          samplingLevelNo: '',
          samplingLevelDesc: '',
          samplingLevelActive: '',
          buDesc: '',
          page: 1,
          limit: 10,
        },
        pageIndex: 1,
        pageSize: 20,
        totalPage: 0,
        height: 200,
        dataList: [],
        dataListLoading: false,
        modalFlag: false,
        modalDisableFlag: false,
        modalData: {
          flag: '',
          site: '',
          bu: '',
          samplingLevelNo: '',
          samplingLevelDesc: '',
          samplingLevelActive: '',
          samplingLevelRemark: '',
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name
        },
        // 标头展示
        columnList: [
          {
            userId: this.$store.state.user.name,
            functionId: 301011,
            serialNumber: '301011TableBuDesc',
            tableId: "301011Table",
            tableName: "检验水平表",
            columnProp: 'buDesc',
            headerAlign: 'center',
            align: "center",
            columnLabel: 'BU',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301011,
            serialNumber: '301011TableSamplingLevelNo',
            tableId: "301011Table",
            tableName: "检验水平表",
            columnProp: 'samplingLevelNo',
            headerAlign: 'center',
            align: "center",
            columnLabel: '检验等级编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301011,
            serialNumber: '301011TableSamplingLevelDesc',
            tableId: "301011Table",
            tableName: "检验水平表",
            columnProp: 'samplingLevelDesc',
            headerAlign: 'center',
            align: "left",
            columnLabel: '检验等级描述',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 200,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301011,
            serialNumber: '301011TableSamplingLevelRemark',
            tableId: "301011Table",
            tableName: "检验水平表",
            columnProp: 'samplingLevelRemark',
            headerAlign: 'center',
            align: "left",
            columnLabel: '备注说明',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 200,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301011,
            serialNumber: '301011TableSamplingLevelActive',
            tableId: "301011Table",
            tableName: "检验水平表",
            columnProp: 'samplingLevelActive',
            headerAlign: 'center',
            align: "center",
            columnLabel: '是否可用',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301011,
            serialNumber: '301011TableCreateDate',
            tableId: "301011Table",
            tableName: "检验水平表",
            columnProp: 'createDate',
            headerAlign: 'center',
            align: "center",
            columnLabel: '创建时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 170,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301011,
            serialNumber: '301011TableCreateBy',
            tableId: "301011Table",
            tableName: "检验水平表",
            columnProp: 'createBy',
            headerAlign: 'center',
            align: "center",
            columnLabel: '创建人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301011,
            serialNumber: '301011TableUpdateDate',
            tableId: "301011Table",
            tableName: "检验水平表",
            columnProp: 'updateDate',
            headerAlign: 'center',
            align: "center",
            columnLabel: '更新时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 170,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301011,
            serialNumber: '301011TableUpdateBy',
            tableId: "301011Table",
            tableName: "检验水平表",
            columnProp: 'updateBy',
            headerAlign: 'center',
            align: "center",
            columnLabel: '更新人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
        ],
        rules: {
          samplingLevelDescType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          samplingLevelActiveType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          bu:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ]
        },
        userBuList: [],
        authSearch: false,
        authSave: false,
        authUpdate: false,
        authDelete: false,
        menuId: this.$route.meta.menuId,
      }
    },

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

    created () {
      // 按钮控制
      this.getButtonAuthData()
      // 获取用户的 site 和 bu
      this.getSiteAndBuByUserName()
      // 校验用户是否收藏
      this.favoriteIsOk()
      // 动态列
      this.getTableUserColumn(this.$route.meta.menuId+'table',1)
      if (!this.authSearch) {
        // 获取数据列表
        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
          }
        })
      },

      // 查询获取数据列表
      getDataList () {
        this.searchData.limit = this.pageSize
        this.searchData.page = this.pageIndex
        samplingLevelSearch(this.searchData).then(({data}) => {
          this.dataList = data.page.list
          this.pageIndex = data.page.currPage
          this.pageSize = data.page.pageSize
          this.totalPage = data.page.totalCount
        })
      },

      // 新增按钮
      addModal () {
        this.modalData = {
          flag: '1',
          bu: this.userBuList[0].buNo,
          site: '',
          samplingLevelNo: '',
          samplingLevelDesc: '',
          samplingLevelActive: 'Y',
          samplingLevelRemark: '',
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name
        }
        this.modalDisableFlag = false
        this.modalFlag = true
      },

      // 修改按钮
      updateModal (row) {
        this.modalData = {
          flag: '2',
          bu: row.site + '_' + row.buNo,
          site: row.site,
          samplingLevelNo: row.samplingLevelNo,
          samplingLevelDesc: row.samplingLevelDesc,
          samplingLevelActive: row.samplingLevelActive,
          samplingLevelRemark: row.samplingLevelRemark,
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name
        }
        this.modalDisableFlag = true
        this.modalFlag = true
      },

      // 删除方法
      deleteModal (row) {
        this.$confirm(`是否删除这个检验等级?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          samplingLevelDelete(row).then(({data}) => {
            if (data && data.code === 0) {
              this.getDataList()
              this.$message.success('操作成功')
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },

      // 新增/修改方法
      saveData () {
        if (this.modalData.bu === '' || this.modalData.bu == null) {
          this.$message.warning('请选择BU！')
          return
        }
        if (this.modalData.samplingLevelDesc === '' || this.modalData.samplingLevelDesc == null) {
          this.$message.warning('请输入检验等级描述！')
          return
        }
        if (this.modalData.samplingLevelActive === '' || this.modalData.samplingLevelActive == null) {
          this.$message.warning('请选择是否在用！')
          return
        }
        if (this.modalData.flag === '1') { // 新增
          samplingLevelSave(this.modalData).then(({data}) => {
            if (data && data.code === 0) {
              this.getDataList()
              this.modalFlag = false
              this.$message.success('操作成功')
            } else {
              this.$message.error(data.msg)
            }
          })
        } else { // 修改
          samplingLevelUpdate(this.modalData).then(({data}) => {
            if (data && data.code === 0) {
              this.getDataList()
              this.modalFlag = false
              this.$message.success('操作成功')
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      },

      // 校验用户是否收藏
      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
          })
        }
      },

      async exportExcel() {
        this.searchData.limit = -1
        this.searchData.page = 1
        excel.exportTable({
          url: "/pms/qc/samplingLevelSearch",
          columnMapping: this.columnList, //可以直接用table，不需要的列就剔除
          mergeSetting: [],//需要合并的列
          params: this.searchData,
          fileName: this.exportName+".xlsx",
          rowFetcher: res => res.data,
          columnFormatter: [],
          dropColumns: [],
        })
      },

      // 动态列开始 获取 用户保存的 格式列
      async getTableUserColumn (tableId, columnId) {
        let queryTableUser = {
          userId: this.$store.state.user.name,
          functionId: this.$route.meta.menuId,
          tableId: tableId,
          status: true,
          languageCode: this.$i18n.locale
        }
        await getTableUserListLanguage(queryTableUser).then(({data}) => {
          if (data.rows.length > 0) {
            switch (columnId) {
              case 1:
                this.columnList = data.rows
                break;
            }
          } else {
            this.getColumnList(tableId, columnId)
          }
        })
      },

      // 获取 tableDefault 列
      async getColumnList (tableId, columnId) {
        let queryTable= {
          functionId: this.$route.meta.menuId,
          tableId: tableId,
          languageCode: this.$i18n.locale
        }
        await getTableDefaultListLanguage(queryTable).then(({data}) => {
          if (data.rows.length !== 0) {
            switch (columnId) {
              case 1:
                this.columnList = data.rows
                break;
            }
          }
        })
      },

      //获取按钮的权限数据
      getButtonAuthData () {
        let searchFlag = this.isAuth(this.menuId+":search")
        let saveFlag = this.isAuth(this.menuId+":save")
        let updateFlag = this.isAuth(this.menuId+":update")
        let deleteFlag = this.isAuth(this.menuId+":delete")
        //处理页面的权限数据
        this.authSearch = !searchFlag
        this.authSave = !saveFlag
        this.authUpdate = !updateFlag
        this.authDelete = !deleteFlag
      },
    }
  }
</script>
<style scoped>
.el-table /deep/ .cell{
  height: auto;
  line-height: 1.5;
}
</style>
