<template>
  <div class="mod-config">

<!--    &lt;!&ndash; 收藏 &ndash;&gt;-->
<!--    <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.site" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'BU'">
        <el-input v-model="searchData.buNo" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchData.status" placeholder="请选择">
          <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-input v-model="searchData.prodLineNo" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'组名称'">
        <el-input v-model="searchData.prodLineDesc" clearable style="width: 120px"></el-input>
      </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>
<!--        <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&#45;&#45;primary el-button&#45;&#45;medium">-->
<!--          {{ "导出" }}-->
<!--        </download-excel>-->
      </el-form-item>
    </el-form>

    <!-- 展示列表 -->
    <el-table
      :height="height"
      :data="dataList"
      border
      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"
        :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="400px">
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;margin-top: -5px;">

        <el-form-item label="工厂编码:" prop="site" :rules="rules.site">
          <el-input v-model="modalData.site" style="width: 150px" :disabled="!isNew"></el-input>
        </el-form-item>
<!--        <el-form-item label="BU:" prop="buNo" >-->
<!--          <el-input v-model="modalData.buNo" style="width: 221px" :disabled="!isNew"></el-input>-->
<!--        </el-form-item>-->

        <el-form-item label="BU" prop="bu" :rules="rules.bu">
          <el-select v-model="modalData.bu" placeholder="请选择" :disabled="modalDisableFlag" style="width: 150px">
            <el-option
              v-for = "i in userBuList"
              :key = "i.buNo"
              :label = "i.sitename"
              :value = "i.buNo">
              <span style="float: left; 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-item label="组编码:" prop="prodLineNo" :rules="rules.prodLineNo">
          <el-input v-model="modalData.prodLineNo" :disabled="modalDisableFlag"  style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="组名称:" prop="prodLineDesc" :rules="rules.prodLineDesc">
          <el-input v-model="modalData.prodLineDesc" style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="备注:" prop="remake" >
          <el-input v-model="modalData.remake" style="width: 150px"></el-input>
        </el-form-item>

        <el-form-item label="状态:">
          <el-select v-model="modalData.status" placeholder="请选择" style="width: 150px">
            <el-option label="启用" value="Y"></el-option>
            <el-option label="禁用" value="N"></el-option>
          </el-select>
        </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 {
  findAll, // 检验方法查询
  saveFanuc, // 检验方法新增
  updateFanuc, // 检验方法修改
  deleteFanuc, // 检验方法删除
} from "@/api/fanucGroup/fanucGroup.js"
import {getSiteAndBuByUserName} from "@/api/eam/eam.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,
        buNo: '',
        prodLineNo: '',
        prodLineDesc: '',
        active: '',
        createBy: this.$store.state.user.name,
        createDate: '',
        updateBy: this.$store.state.user.name,
        updateDate: '',
        remake: '',
        status: '',
        page: 1,
        limit: 10,
      },
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      height: 200,
      dataList: [],
      dataListLoading: false,
      modalFlag: false,
      modalDisableFlag: false,
      modalData: {
        site: this.$store.state.user.site,
        bu: '',
        buNo: '',
        prodLineNo: '',
        prodLineDesc: '',
        active: '',
        createBy: this.$store.state.user.name,
        createDate: '',
        updateBy: this.$store.state.user.name,
        updateDate: '',
        remake: '',
        status: ''
      },
      // 标头展示
      columnList: [
        {
          userId: this.$store.state.user.name,
          functionId: 501001,
          serialNumber: '501001TableSite',
          tableId: "501001Table",
          tableName: "工厂编码",
          columnWidth: 150,
          columnProp: 'site',
          headerAlign: 'center',
          align: "center",
          columnLabel: '工厂编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
        },
        {
          userId: this.$store.state.user.name,
          functionId: 501001,
          serialNumber: '501001TableBuNo',
          tableId: "501001Table",
          tableName: "BU",
          columnWidth: 150,
          columnProp: 'buNo',
          headerAlign: 'center',
          align: "left",
          columnLabel: 'Bu',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
        },
        {
          userId: this.$store.state.user.name,
          functionId: 501001,
          serialNumber: '501001TableProdLineNo',
          tableId: "501001Table",
          tableName: "组编码",
          columnWidth: 150,
          columnProp: 'prodLineNo',
          headerAlign: 'center',
          align: "left",
          columnLabel: '组编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
        },
        {
          userId: this.$store.state.user.name,
          functionId: 501001,
          serialNumber: '501001TableProdLineDesc',
          tableId: "501001Table",
          tableName: "组名称",
          columnWidth: 140,
          columnProp: 'prodLineDesc',
          headerAlign: 'center',
          align: "left",
          columnLabel: '组名称',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
        },
        // {
        //   userId: this.$store.state.user.name,
        //   functionId: 501001,
        //   serialNumber: '501001TableActive',
        //   tableId: "501001Table",
        //   tableName: "仓库类型",
        //   columnWidth: 150,
        //   columnProp: 'active',
        //   headerAlign: 'center',
        //   align: "center",
        //   columnLabel: '仓库类型',
        //   columnHidden: false,
        //   columnImage: false,
        //   columnSortable: false,
        //   sortLv: 0,
        //   status: true,
        //   fixed: '',
        // },
        {
          userId: this.$store.state.user.name,
          functionId: 501001,
          serialNumber: '501001TableCreateBy',
          tableId: "501001Table",
          tableName: "创建人",
          columnWidth: 140,
          columnProp: 'createBy',
          headerAlign: 'center',
          align: "left",
          columnLabel: '创建人',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
        },
        {
          userId: this.$store.state.user.name,
          functionId: 501001,
          serialNumber: '501001TableCreateDate',
          tableId: "501001Table",
          tableName: "创建时间",
          columnWidth: 150,
          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: 501001,
          serialNumber: '501001TableUpdateBy',
          tableId: "501001Table",
          tableName: "修改人",
          columnWidth: 140,
          columnProp: 'updateBy',
          headerAlign: 'center',
          align: "center",
          columnLabel: '修改人',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
        },
        {
          userId: this.$store.state.user.name,
          functionId: 501001,
          serialNumber: '501001TableUpdateDate',
          tableId: "501001Table",
          tableName: "修改时间",
          columnWidth: 150,
          columnProp: 'updateDate',
          headerAlign: 'center',
          align: "left",
          columnLabel: '修改时间',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
        },
        {
          userId: this.$store.state.user.name,
          functionId: 501001,
          serialNumber: '501001TableRemake',
          tableId: "501001Table",
          tableName: "备注",
          columnWidth: 140,
          columnProp: 'remake',
          headerAlign: 'center',
          align: "left",
          columnLabel: '备注',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
        },
        {
          userId: this.$store.state.user.name,
          functionId: 501001,
          serialNumber: '501001TableStatus',
          tableId: "501001Table",
          tableName: "状态",
          columnWidth: 125,
          columnProp: 'status',
          headerAlign: 'center',
          align: "center",
          columnLabel: '状态',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
        },
      ],
      rules: {
        prodLineNo:[
          {
            required: true,
            message: ' ',
            trigger: ['blur','change']
          }
        ],
        prodLineDesc:[
          {
            required: true,
            message: ' ',
            trigger: ['blur','change']
          }
        ],
        site:[
          {
            required: true,
            message: ' ',
            trigger: ['blur','change']
          }
        ],
        bu:[
          {
            required: true,
            message: ' ',
            trigger: ['blur','change']
          }
        ]
      },
      options: [],
      userBuList: [],
      authSearch: false,
      authSave: false,
      authUpdate: false,
      authDelete: false,
      menuId: this.$route.meta.menuId,
    }
  },



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

  //编码自动转化成大写
  watch: {
    modalData: {
      deep: true,
      handler: function (newV, oldV) {
        this.modalData.prodLineNo = this.modalData.prodLineNo.toUpperCase()
      }
    }
  },

  created () {
    //页面在加载的时候就调用查询方法
    // 获取用户的 site 和 bu
    this.getSiteAndBuByUserName()
  },


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

    // // 初始化组件的参数
    // init (currentRow) {
    //   //初始化参数
    //   this.pageData = JSON.parse(JSON.stringify(currentRow))
    //   //打开页面
    //   this.visible = true
    //   //判断是否是新增
    //   if (this.pageData.addFlag === 'Y') {
    //     this.modalDisableFlag = false
    //     this.pageData.bu = this.userBuList[0].buNo
    //   } else {
    //     this.pageData.bu = this.pageData.site + '_' + this.pageData.buNo
    //     this.modalDisableFlag = true
    //   }
    //   //重置人员信息
    //   this.pageData.username = this.userId
    // },


    // 查询获取数据列表
    getDataList () {
      this.searchData.limit = this.pageSize
      this.searchData.page = this.pageIndex
      findAll(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,
        bu: this.userBuList[0].buNo,
        prodLineNo: '',
        prodLineDesc: '',
        active: '',
        createBy: '',
        createDate: '',
        updateBy: '',
        updateDate: '',
        remake: '',
        status: 'Y',

      }
      this.modalDisableFlag = false
      this.modalFlag = true
    },

    // 修改按钮
    updateModal (row) {
      this.modalData = {
        flag: '2',
        bu: row.site + '_' + row.buNo,
        id:row.id,
        site: row.site,
        creator: this.$store.state.user.name,
        buNo: row.buNo,
        prodLineNo: row.prodLineNo,
        active: row.active,
        prodLineDesc: row.prodLineDesc,
        createBy: row.createBy,
        createDate: row.createDate,
        updateBy: row.updateBy,
        remake: row.remake,
        status: row.status
      }
      this.modalDisableFlag = true
      this.modalFlag = true
    },

    // 删除方法
    deleteModal (row) {
      this.$confirm(`是否删除此数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFanuc(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.prodLineNo === '' || this.modalData.prodLineNo == null) {
        this.$message.warning('请输入组编码！')
        return
      }
      if(this.modalData.prodLineDesc === ''|| this.modalData.prodLineDesc == null){
        this.$message.warning('请输入组名称！')
        return
      }
      if (this.modalData.flag === '1') { // 新增
        saveFanuc(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 { // 修改
        updateFanuc(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 findAll(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) {
      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.
        }
      })
    },

    //获取按钮的权限数据
    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>
