<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">
      <el-form-item>
        <excelUpload v-on:excelUploadChild="excelUploadChild"></excelUpload>
      </el-form-item>
      <el-form-item>
        <el-button @click="batchOut" type="primary">{{ buttons.outList }}</el-button>
        <el-button @click="saveColumnList()" type="primary" v-show="showDefault">{{ buttons.defaultTable }}</el-button>
        <el-button @click="userSetting" type="primary">{{ buttons.settingTable }}</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"
        :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="150"
        :label="buttons.cz">
        <template slot-scope="scope">
          <a type="text" size="small" @click="deleteRoll(scope.row)" herf="#">{{ buttons.delete }}</a>
        </template>
      </el-table-column>

    </el-table>
    <!-- 设置列 -->
    <column v-if="visible" ref="column" @refreshData="getTableUserColumn"></column>

  </div>
</template>

<script>
import excelUpload from "../common/excelUpload";
import AddOrUpdate from './crollinfo-add-or-update'
import {getCRollInfoList, batchRollUpdateStatus} from '@/api/crollinfo/crollinfo.js'
import column from "../common/column";
import search from "../common/search";
import {
  searchSysLanguageParam,
  searchFunctionButtonList,
  saveButtonList,
} from "@/api/sysLanguage.js"
import {
  saveTableDefaultList,
  getTableDefaultListLanguage,
  getTableUserListLanguage,
  removerDefault,
  removerUser
} from "@/api/table.js"
import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'

export default {
  data() {
    return {
      searchVisible: false,
      searchShow: false,
      // table高度
      height: 450,
      // 是否收藏
      favorite: false,
      addLanguage: false,
      functionId: this.$route.meta.menuId,
      tableId: "105002003OO",
      languageCode: this.$i18n.locale,
      queryTable: {
        functionId: this.$route.meta.menuId,
        tableId: "105002003OO",
        languageCode: this.$i18n.locale
      },
      visible: false,
      showDefault: false,
      queryData: {
        day: '',
        rollno: '',
        partno: ''
      },
      // 语言词典集合
      sysLanguageParams: [],
      columnList: [
        {
          "userId": this.$store.state.user.name,
          "tableId": "105002003OO",
          "tableName": "其它出库",
          "columnProp": "rollno",
          "columnLabel": "卷号",
          "columnHidden": false,
          "columnImage": false,
          "columnSortable": false,
          "columnWidth": 100,
          "format": null,
          "sortLv": 0,
          "status": true,
          "fixed": true,
          "serialNumber": null,
          "columnType": "string",
          "align": null
        },
        {
          "userId": this.$store.state.user.name,

          "tableId": "105002003OO",
          "tableName": "其它出库",
          "columnProp": "partno",
          "columnLabel": "物料编号",
          "columnHidden": false,
          "columnImage": false,
          "columnSortable": false,
          "columnWidth": 100,
          "format": null,
          "sortLv": 1,
          "status": true,
          "fixed": false,
          "serialNumber": null,
          "columnType": "string",
          "align": null
        },
        {
          "userId": this.$store.state.user.name,

          "tableId": "105002003OO",
          "tableName": "其它出库",
          "columnProp": "partDescription",
          "columnLabel": "物料描述",
          "columnHidden": false,
          "columnImage": false,
          "columnSortable": false,
          "columnWidth": 250,
          "format": null,
          "sortLv": 2,
          "status": true,
          "fixed": false,
          "serialNumber": null,
          "columnType": "string",
          "align": null
        },
        {
          "userId": this.$store.state.user.name,

          "tableId": "105002003OO",
          "tableName": "其它出库",
          "columnProp": "site",
          "columnLabel": "工厂编号",
          "columnHidden": false,
          "columnImage": false,
          "columnSortable": false,
          "columnWidth": 80,
          "format": null,
          "sortLv": 3,
          "status": true,
          "fixed": false,
          "serialNumber": null,
          "columnType": "string",
          "align": null
        },
        {
          "userId": this.$store.state.user.name,

          "tableId": "105002003OO",
          "tableName": "其它出库",
          "columnProp": "status",
          "columnLabel": "状态",
          "columnHidden": false,
          "columnImage": false,
          "columnSortable": false,
          "columnWidth": 80,
          "format": null,
          "sortLv": 5,
          "status": true,
          "fixed": false,
          "serialNumber": null,
          "columnType": "number",
          "align": null
        },
        {
          "userId": this.$store.state.user.name,

          "tableId": "105002003OO",
          "tableName": "其它出库",
          "columnProp": "rolltype",
          "columnLabel": "卷类型",
          "columnHidden": false,
          "columnImage": false,
          "columnSortable": false,
          "columnWidth": 80,
          "format": null,
          "sortLv": 7,
          "status": true,
          "fixed": false,
          "serialNumber": null,
          "columnType": "string",
          "align": null
        },
        {
          "userId": this.$store.state.user.name,

          "tableId": "105002003OO",
          "tableName": "其它出库",
          "columnProp": "rollqty",
          "columnLabel": "卷数量",
          "columnHidden": false,
          "columnImage": false,
          "columnSortable": false,
          "columnWidth": 80,
          "format": null,
          "sortLv": 8,
          "status": true,
          "fixed": false,
          "serialNumber": null,
          "columnType": "number",
          "align": null
        },
      ],
      dataList: [],
      buttons: {
        add: '添加',
        edit: '编辑',
        delete: '删除',
        deleteList: '批量删除',
        outList: '出库',
        cz: '操作',
        search: '搜索',
        download: '导出',
        settingTable: '设置列表',
        defaultTable: '设置默认配置'
      },
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    }
  },
  components: {
    AddOrUpdate,
    column,
    search,
    excelUpload
  },
  mounted() {
    this.$nextTick(() => {
      this.height = window.innerHeight - 165;
    })
  },
  activated() {
  },

  methods: {
    // 批量出库
    async batchOut() {
      if (this.dataList.length === 0) {
        this.$message.warning("请先导入数据!")
      } else {
        let status = JSON.parse(JSON.stringify(this.dataList)).filter(item => item.statusDb !== 'I')
        let flag = true
        if (status.length > 0) {
          this.$message.warning("数据中包含不在库的卷!")
          await this.$confirm('数据中包含不在库的卷, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

          }).catch(() => {
            flag = false
          });
        }
        if (flag){
          let dataList = JSON.parse(JSON.stringify(this.dataList)).filter(item => item.statusDb === 'I').map(item => {
            item.statusDb = 'D'
            item.status = '已消耗'
            return item;
          })
          batchRollUpdateStatus(dataList).then(({data}) => {
            if (data.code === 0) {
              this.dataList = []
              this.$message.success('出库成功')
            } else {
              this.$message.warning('出库失败')
            }

          })
        }

      }
    },
    // 移除行
    deleteRoll(row) {
      this.dataList = this.dataList.filter(item => item.rollno !== row.rollno)
    },
    excelUploadChild(childValue) {
      // childValue就是子组件传过来的值
      if (childValue.list.length > 0) {
        this.dataList = childValue.list
        this.$message.success("导入数据成功")
      } else {
        this.$message.warning("导入数据失败,请检查导入的数据")
      }


    },
    // 校验用户是否收藏
    favoriteIsOk() {
      let userFavorite = {
        userId: this.$store.state.user.id,
        languageCode: this.$i18n.locale
      }
      userFavoriteList(userFavorite).then(({data}) => {
        let size = data.list.filter(item => item.menuId == this.$route.meta.menuId).length;
        if (size > 0) {
          this.favorite = true
        } else {
          this.favorite = false
        }
      })
    },
    // 收藏 OR 取消收藏
    favoriteFunction() {
      let userFavorite = {
        userId: this.$store.state.user.id,
        functionId: this.$route.meta.menuId,
      }
      if (this.favorite) {
        // 取消收藏
        this.$confirm(`确定取消收藏`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          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
        })
      }

    },
    // 获取button的词典
    getFunctionButtonList() {
      let queryButton = {
        functionId: this.functionId,
        tableId: this.tableId,
        languageCode: this.languageCode,
        objectType: 'button'
      }
      searchFunctionButtonList(queryButton).then(({data}) => {
        if (data.data.length > 0) {
          this.buttons = data.data
        }
      })
    },
    // 获取语言词典
    getSysLanguageParamList() {
      let querySysLanguageParam = {
        languageCode: this.$i18n.locale
      }
      searchSysLanguageParam(querySysLanguageParam).then(({data}) => {
        this.sysLanguageParams = data.rows
      })
    },
    // 打开页面设置
    userSetting() {
      this.visible = true;
      let queryTable = {
        userId: this.userId,
        functionId: this.functionId,
        tableId: this.tableId,
        languageCode: this.languageCode
      }
      this.$nextTick(() => {
        this.$refs.column.init(queryTable);
      });
    },
    // 获取 用户保存的 格式列
    getTableUserColumn() {
      let queryTableUser = {
        userId: this.userId,
        functionId: this.functionId,
        tableId: this.tableId,
        languageCode: this.languageCode,
        objectType: 'table',
        status: true,
      }
      getTableUserListLanguage(queryTableUser).then(({data}) => {
        if (data.rows.length > 0) {
          //this.columnList = []
          this.columnList = data.rows
        } else {
          this.getColumnList()
        }

      })
    },
    // 保存 默认配置 列
    async saveColumnList() {
      // 删除所有的该页面下保存的数据
      if (this.userColumnList) {
        //删除 user自定义的数据
        await removerUser(this.queryTable)
      }
      // 删除默认配置
      await removerDefault(this.queryTable)
      // 保存页面 table属性
      let sumColumnList = this.columnList;
      sumColumnList = sumColumnList.map(item => {
        return item = {
          tableId: item.tableId,
          tableName: item.tableName,
          columnProp: item.columnProp,
          columnLabel: item.columnLabel,
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          columnWidth: item.columnWidth,
          format: item.format,
          functionId: this.$route.meta.menuId,
          sortLv: item.sortLv,
          status: true,
          fixed: item.fixed,
          serialNumber: item.serialNumber,
          columnType: item.columnType,
          align: item.align
        }
      })

      await saveTableDefaultList(sumColumnList)
      // 保存页面 button label title 属性
      let buttons = this.buttonList.map(item => {
        return item = {
          functionId: this.$route.meta.menuId,
          languageValue: item.languageValue,
          objectId: item.objectId,
          objectType: item.objectType,
          tableId: item.tableId
        }
      })
      await saveButtonList(buttons)
      this.getFunctionButtonList()
      this.getColumnList()
    },
    // // 保存 默认配置 列
    // saveColumnList() {
    //   // this.showDefault = false
    //   saveButtonList(this.buttonList).then(({data}) => {
    //   })
    //   saveTableDefaultList(this.columnList).then(({data}) => {
    //     if (data.code == 0) {
    //       this.$message.success(data.msg)
    //       // this.showDefault = false
    //     } else {
    //      // this.showDefault = true
    //       this.$message.error(data.msg)
    //     }
    //   })
    //   this.getFunctionButtonList();
    //   this.getColumnList()
    // },
    // 获取 tableDefault 列
    getColumnList() {
      let queryTable = {
        functionId: this.functionId,
        tableId: this.tableId,
        languageCode: this.languageCode
      }
      getTableDefaultListLanguage(queryTable).then(({data}) => {
        if (!data.rows.length == 0) {
          // this.showDefault = false
          this.columnList = data.rows
        } else {
          // this.showDefault = true
        }
      })
    },

  },
  created() {
    this.getTableUserColumn()
    this.getSysLanguageParamList()
    this.getFunctionButtonList()
    this.favoriteIsOk()
  }
}
</script>
<style scoped>
.sl-svg {
  overflow: hidden;
  float: right;
}

.el-button--small, .el-button--small.is-round {
  padding: 5px 10px;
}
</style>
