<template>
  <div class="mod-config">
    <!-- 收藏 -->
    <div>
      <span @click="favoriteFunction()">
        <icon-svg :name="favorite?'xiangqufill':'xiangqu'" class="sl-svg"></icon-svg>
      </span>
    </div>
    <!-- 条件查询 -->
    <el-form :inline="true" label-position="top" :model="searchData" @keyup.enter.native="getDataList()">
      <el-form-item :label="'方法编码:'">
        <el-input v-model="searchData.methodNo" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'方法名称:'">
        <el-input v-model="searchData.methodName" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="检验类型:">
        <el-select v-model="searchData.inspectionTypeNo" placeholder="请选择">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for = "i in options"
            :key = "i.inspectionTypeNo"
            :label = "i.inspectionTypeName"
            :value = "i.inspectionTypeNo">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="' '">
        <el-button type="primary" @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-->
<!--        prop="methodNo"-->
<!--        header-align="center"-->
<!--        align="center"-->
<!--        label="方法编码"-->
<!--        width="100">-->
<!--      </el-table-column>-->
<!--      <el-table-column-->
<!--        prop="methodName"-->
<!--        header-align="center"-->
<!--        align="left"-->
<!--        label="方法名称"-->
<!--        :width="flexColumnWidth('方法名称','methodName')">-->
<!--      </el-table-column>-->
<!--      <el-table-column-->
<!--        prop="methodRemark"-->
<!--        header-align="center"-->
<!--        align="left"-->
<!--        label="方法说明"-->
<!--        :width="flexColumnWidth('方法说明','methodRemark')">-->
<!--      </el-table-column>-->
      <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"
        :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="160"
        label="操作">
        <template slot-scope="scope">
          <a type="text" size="small" @click="updateModal(scope.row)">修改</a>
          <a type="text" size="small" @click="deleteModal(scope.row)">删除</a>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[20, 50, 100, 200, 500]"
      :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="500px">
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item label="方法名称:" prop="methodName" :rules="rules.methodNameType">
          <el-input v-model="modalData.methodName" style="width: 221px"></el-input>
        </el-form-item>
        <el-form-item label="检验类型:" prop="inspectionTypeNo" :rules="rules.inspectionTypeNoType">
          <el-select v-model="modalData.inspectionTypeNo" placeholder="请选择" style="width: 221px">
            <el-option
              v-for = "i in options"
              :key = "i.inspectionTypeNo"
              :label = "i.inspectionTypeName"
              :value = "i.inspectionTypeNo">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true" label-position="top" :model="modalData" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item :label="'检验方法说明:'">
          <el-input v-model="modalData.methodRemark" style="width: 456px"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="height:40px;margin-top: 20px;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 {
    qcMethodSearch, // 检验方法查询
    qcMethodSave, // 检验方法新增
    qcMethodUpdate, // 检验方法修改
    qcMethodDelete, // 检验方法删除
    inspectionTypeSearch, // 搜索所有检验类型
  } from "@/api/qc/qc.js"
  import {
    getTableDefaultListLanguage,
    getTableUserListLanguage,
  } from "@/api/table.js"
  import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'
  export default {
    data () {
      return {
        // 是否收藏
        favorite: false,
        // 导出 start
        exportData: [],
        exportName: "检验方法" + this.dayjs().format('YYYYMMDDHHmmss'),
        exportHeader: ["检验方法"],
        exportFooter: [],
        exportList:[],
        // 导出 end
        searchData: {
          site: this.$store.state.user.site,
          methodNo: '',
          methodName: '',
          inspectionTypeNo: '',
          page: 1,
          limit: 10,
        },
        pageIndex: 1,
        pageSize: 50,
        totalPage: 0,
        height: 200,
        dataList: [],
        dataListLoading: false,
        modalFlag: false,
        modalDisableFlag: false,
        methodData: {
          methodNo: '',
          valueNo: '',
          availableValue: '',
          createBy: this.$store.state.user.name
        },
        modalData: {
          site: this.$store.state.user.site,
          flag: '',
          methodNo: '',
          methodName: '',
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
          methodRemark: '',
          inspectionTypeNo: ''
        },
        // 标头展示
        columnList: [
          {
            userId: this.$store.state.user.name,
            functionId: 301001,
            serialNumber: '301001TableMethodNo',
            tableId: "301001Table",
            tableName: "检验方法维护表",
            columnWidth: 185,
            columnProp: 'methodNo',
            headerAlign: 'center',
            align: "center",
            columnLabel: '方法编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301001,
            serialNumber: '301001TableMethodName',
            tableId: "301001Table",
            tableName: "检验方法维护表",
            columnWidth: 182,
            columnProp: 'methodName',
            headerAlign: 'center',
            align: "center",
            columnLabel: '方法名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301001,
            serialNumber: '301001TableMethodRemark',
            tableId: "301001Table",
            tableName: "检验方法维护表",
            columnWidth: 182,
            columnProp: 'methodRemark',
            headerAlign: 'center',
            align: "center",
            columnLabel: '方法说明',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301001,
            serialNumber: '301001TableInspectionTypeName',
            tableId: "301001Table",
            tableName: "检验方法维护表",
            columnWidth: 182,
            columnProp: 'inspectionTypeName',
            headerAlign: 'center',
            align: "center",
            columnLabel: '检验类型',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301001,
            serialNumber: '301001TableCreateDate',
            tableId: "301001Table",
            tableName: "检验方法维护表",
            columnWidth: 182,
            columnProp: 'createDate',
            headerAlign: 'center',
            align: "center",
            columnLabel: '创建时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301001,
            serialNumber: '301001TableCreateBy',
            tableId: "301001Table",
            tableName: "检验方法维护表",
            columnWidth: 182,
            columnProp: 'createBy',
            headerAlign: 'center',
            align: "center",
            columnLabel: '创建人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301001,
            serialNumber: '301001TableUpdateDate',
            tableId: "301001Table",
            tableName: "检验方法维护表",
            columnWidth: 182,
            columnProp: 'updateDate',
            headerAlign: 'center',
            align: "center",
            columnLabel: '更新时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301001,
            serialNumber: '301001TableUpdateBy',
            tableId: "301001Table",
            tableName: "检验方法维护表",
            columnWidth: 182,
            columnProp: 'updateBy',
            headerAlign: 'center',
            align: "center",
            columnLabel: '更新人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
        ],
        rules:{
          methodNameType:[
            {
              required: true,
              message: ' ',
              trigger: 'change'
            }
          ],
          inspectionTypeNoType:[
            {
              required: true,
              message: ' ',
              trigger: 'change'
            }
          ]
        },
        options: [],
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.height = window.innerHeight - 180
      })
    },
    created () {
      this.getDataList()
      this.favoriteIsOk()
      this.inspectionTypeSearch()
      // 动态列
      this.getTableUserColumn(this.$route.meta.menuId+'table',1)
    },
    methods: {
      /**
       *  自适应
       * @param label
       * @param prop
       * @returns {string}
       */
      flexColumnWidth (label, prop) {
        // 1.获取该列的所有数据
        const arr = this.dataList.map(x => x[prop])
        arr.push(label) // 把每列的表头也加进去算
        // 2.计算每列内容最大的宽度 + 表格的内间距（依据实际情况而定）
        return (this.getMaxLength(arr) + 25) + 'px'
      },
      getTextWidth (str) {
        let width = 0
        const html = document.createElement('span')
        html.innerText = str
        html.className = 'getTextWidth'
        document.querySelector('body').appendChild(html)
        width = document.querySelector('.getTextWidth').offsetWidth
        document.querySelector('.getTextWidth').remove()
        return width
      },
      getMaxLength (arr) {
        return arr.reduce((acc, item) => {
          if (item) {
            const calcLen = this.getTextWidth(item)
            if (acc < calcLen) {
              acc = calcLen
            }
          }
          return acc
        }, 0)
      },
      // 查询获取数据列表
      getDataList () {
        this.searchData.limit = this.pageSize
        this.searchData.page = this.pageIndex
        qcMethodSearch(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
          }
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 新增按钮
      addModal () {
        this.modalData = {
          flag: '1',
          site: this.$store.state.user.site,
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
          methodNo: '',
          methodName: '',
          methodRemark: '',
          inspectionTypeNo: ''
        }
        this.modalDisableFlag = false
        this.modalFlag = true
      },
      // 修改按钮
      updateModal (row) {
        this.modalData = {
          flag: '2',
          site: this.$store.state.user.site,
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
          methodNo: row.methodNo,
          methodName: row.methodName,
          methodRemark: row.methodRemark,
          inspectionTypeNo: row.inspectionTypeNo
        }
        this.modalDisableFlag = true
        this.modalFlag = true
      },
      // 删除方法
      deleteModal (row) {
        this.$confirm(`是否删除这个检验方法?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          qcMethodDelete(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.methodName === '' || this.modalData.methodName == null) {
          this.$message.warning('请输入检验方法名称！')
          return
        }
        if(this.modalData.inspectionTypeNo === ''|| this.modalData.inspectionTypeNo == null){
          this.$message.warning('请选择检验类型！')
          return
        }
        if (this.modalData.flag === '1') { // 新增
          qcMethodSave(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: '确定'
              })
            }
          })
        } else { // 修改
          qcMethodUpdate(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: '确定'
              })
            }
          })
        }
      },
      // 查询检验类型
      inspectionTypeSearch(){
        let tempData = {
          site: this.$store.state.user.site
        }
        inspectionTypeSearch(tempData).then(({data}) => {
          if (data.code === 0) {
            this.options = data.rows
          }
        })
      },

      // 校验用户是否收藏
      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 qcMethodSearch(this.searchData).then(({data}) => {
          this.exportList= data.rows;
        })
        return this.exportList;
      },
      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
      },
      // 动态列开始 获取 用户保存的 格式列
      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) {
            //this.columnList1 = []
            switch (columnId) {
              case 1:
                this.columnList = data.rows
                break;
              // case 2:
              //   this.columnDetailList = data.rows
              //   break;
              // case 3:
              //   this.columnList2 = data.rows
              //   break;
              // case 4:
              //   this.columnList3 = data.rows
              //   break;
            }

          } else {
            this.getColumnList(tableId, columnId)
          }
        })

      },

      // 获取 tableDefault 列
      async getColumnList(tableId, columnId) {
        this.queryTable.tableId = tableId
        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;
              // case 2:
              //   this.columnDetailList = data.rows
              //   break;
              // case 3:
              //   this.columnList2 = data.rows
              //   break;
              // case 4:
              //   this.columnList3 = data.rows
              //   break;
            }
          } else {
            // this.showDefault = true.
          }
        })

      },
      //动态列结束
    }
  }
</script>
