<template>
  <div class="app-container">
    <div v-if="isPercentage" class="percentage" style="width: 210px;height: 90px;background: #fff;position: fixed;bottom: 0;left: 0;z-index: 9999999999999;">
      <h4 style="padding-left: 10px;line-height: 0;">导出进度：</h4>
      <el-progress style="padding-left: 10px;" :text-inside="true" :stroke-width="26" :percentage="percentage" />
    </div>
    <div class="filter-container">
      <el-input v-model="getdataListParm.parammaps.brandName" placeholder="品牌名" style="width: 140px;" class="filter-item" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>

      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleDownload">导出</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      class="elTable"
      @sort-change="tableSort"
      :max-height="myHeight"
    >
      <el-table-column label="序号" align="center" type="index" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + (pageNum-1) * pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌名称" min-width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.brandName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资产数" sortable prop="eqs" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.eqs }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备件数" sortable prop="prs" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.prs }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同数" sortable prop="cts" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.cts }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备类型数" sortable prop="bps" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.bps }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" min-width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="启用" min-width="80px" header-align="center" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="handleEnableChange(scope.$index, scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="400px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="success" size="mini" @click="handleeqMenu(row)">设备</el-button>
          <el-button type="success" size="mini" @click="handlePartMenu(row)">备件</el-button>
          <el-button v-if="isBrandUpdate" type="success" size="mini" @click="form_edit(row)">编辑</el-button>
          <el-button v-if="isBrandDelete && row.bps === 0 && row.eqs === 0 && row.prs === 0 && row.cts === 0" size="mini" type="danger" @click="form_delete(row)"> 删除 </el-button>
          <!-- <el-button type="danger" size="mini" @click="form_delete(row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="getdataListParm.offset" :limit.sync="getdataListParm.pagecount" @pagination="get_table_data" />
    <!-- 弹出层新增or修改 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="50%">
      <el-form ref="temp" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 90%; margin-left:50px;">
        <el-row>
          <el-col :span="8">
            <el-form-item label="品牌名称" prop="brandName">
              <el-input ref="brandName" v-model="temp.brandName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="temp.createTime"
              type="date"
              placeholder="选择日期"
              style="width:170px;"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            />
          </el-form-item> -->

          <!-- <el-col :span="8">
            <el-form-item label="创建时间" prop="createTime">
              <el-input ref="createTime" v-model="temp.createTime" />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogStatus==='create'" ref="createb" :disabled="isokDisable" type="success" @click="add_dialog_save_again()">保存并新增</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?add_dialog_save():edit_dialog_save()">保存并关闭</el-button>
        <el-button @click="dialogFormVisible = false">取消并关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap['stock']" :visible.sync="dialogstockVisible" :close-on-click-modal="false">
      <el-form :rules="rules" label-position="left" label-width="150px" style="width: 800px; margin-left:50px;">
        <el-form-item label="可提供的备件类别" prop="stockname">
          <tree-select
            :disabled="disabled"
            :height="280"
            :width="400"
            size="small"
            multiple
            :data="parentstock"
            :default-props="defaultProps"
            collapse-tags
            :node-key="nodeKey"
            :checked-keys="defaultCheckedKeys"
            @popoverHide="popoverHide"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updatestock()"> 确认 </el-button>
        <el-button @click="dialogstockVisible = false"> 关闭 </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap['eq']" :visible.sync="dialogeqVisible" :close-on-click-modal="false">
      <el-form :rules="rules" label-position="left" label-width="150px" style="width: 800px; margin-left:50px;">
        <el-form-item label="可提供的设备类别" prop="eqname">
          <tree-select
            :disabled="disabled"
            :height="280"
            :width="400"
            size="small"
            multiple
            :data="parenteq"
            :default-props="eq_defaultProps"
            collapse-tags
            :node-key="eq_nodeKey"
            :checked-keys="eq_defaultCheckedKeys"
            @popoverHide="eq_popoverHide"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateeq()"> 确认 </el-button>
        <el-button @click="dialogeqVisible = false"> 关闭 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
import { GetDataByName, GetDataByNames, PostDataByName, GetAccount, UpdateDataRelation, transData, checkButtons, failproccess, formatJson } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime, sortChange } from '@/utils/index.js'
// eslint-disable-next-line no-unused-vars
import { validateEMail } from '@/utils/validate.js'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'
import TreeSelect from '@/components/TreeSelect'
import Cookies from 'js-cookie'
export default {
  name: 'Product',
  components: { Pagination, TreeSelect },
  directives: { waves },
  data() {
    return {
      myHeight:document.documentElement.clientHeight - 85- 150,
      disabled: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      requestParam: {
        name: 'insertAsset',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      // 1-2:table&搜索传参
      getdataListParm: {
        name: 'getBrandList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          brandName: ''
        }
      },
      getMenuParm: { name: 'getBrandRecu',
        idname: 'id'
        // params: [-1]
      },
      // 2-3：下拉框请求后数据加入[]
      findAllPasture: [],

      // 2-1.请求下拉框接口
      requestParams: [
        { name: 'findAllPasture', offset: 0, pagecount: 0, params: [] }
      ],

      temp: {},

      // 备件选择开始
      getStockParm: { name: 'getpart_classList' },
      parentstock: [],
      nodeKey: 'id',
      defaultCheckedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'partClassName'
      },
      dialogstockVisible: false,
      selectedstock: '',
      dataform: {
        id: '',
        name: '',
        selectedstock: [],
        sort: '',
        enable: ''
      },
      UpdateDataRelationParam: {
        name: '',
        dataname: '',
        datavalue: '',
        valuename: '',
        values: ''
      },
      // 备件选择结束
      // 设备选择开始
      getEQParm: { name: 'geteqclasslist' },
      parenteq: [],
      eq_nodeKey: 'id',
      eq_defaultCheckedKeys: [],
      eq_defaultProps: {
        children: 'children',
        label: 'typeName'
      },
      dialogeqVisible: false,
      selectedeq: '',
      eq_dataform: {
        id: '',
        name: '',
        selectedeq: [],
        sort: '',
        enable: ''
      },

      // 设备选择结束
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        munu: '品牌菜单'
      },
      // 校验规则
      rules: {
        assetNumber: [
          { required: true, message: '必填', trigger: 'blur' }
          // 引入自定义校验并使用
          // { validator: validateEMail, trigger: 'blur' }
        ],
        equipmentName: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      buttons: [],
      isBrandDelete: [],
      isBrandUpdate: [],
      isPercentage: false,
      percentage: 1
    }
  },
  created() {
    const that = this
    GetDataByName({ 'name': 'getUserPCButtons', 'parammaps': { 'jwt_username': Cookies.get('name') }}).then(response => {
      that.buttons = response.data.list
      that.get_auto_buttons()
    })
    this.get_select_list()
    this.get_table_data()
  },

  methods: {
    tableSort(column) {
      sortChange(column, this.list)
    },
    get_auto_buttons() {
      // 删除
      const BrandDelete = 'basic:brand:delete'
      const isBrandDelete = checkButtons(this.$store.state.user.buttons, BrandDelete)
      this.isBrandDelete = isBrandDelete
      // 编辑
      const BrandUpdate = 'basic:brand:update'
      const isBrandUpdate = checkButtons(this.$store.state.user.buttons, BrandUpdate)
      this.isBrandUpdate = isBrandUpdate
    },
    // 供应商模糊查询
    providerSearch(queryString, cb) {
      var returnList = this.findAllProvider
      var results = queryString
        ? returnList.filter(this.createFilter(queryString))
        : returnList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return returnValue => {
        return (
          returnValue.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        )
      }
    },
    handleSelect(item) {
      console.log(item)
    },
    // 1-1: table&搜索
    get_table_data() {
      this.listLoading = true
      GetDataByName(this.getdataListParm).then(response => {
        this.list = response.data.list
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        if (response.data.total) {
          this.total = response.data.total
        }
        this.getStockList()
        this.geteqList()
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    // 2-2：下拉框
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllPasture = response.data.findAllPasture.list
      })
    },
    form_search() {
      this.listLoading = true
      this.getdataListParm.offset = 1
      this.get_table_data()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    form_reset() {
      this.temp = {
        // 格式化日期
        inputDatetime: parseTime(new Date(), '{y}-{m}-{d}')
      }
    },
    form_add() {
      this.form_reset()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      // this.temp.pastureId = this.$store.state.user.pastureid
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    add_dialog_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'insertBrand'
          this.requestParam.parammaps = this.temp
          // console.log('牧场主键:'+this.temp.pastureId)
          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.get_table_data()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },
    add_dialog_save_again() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate((valid) => {
        if (valid) {
          this.requestParam.parammaps = this.temp
          this.requestParam.name = 'insertBrand'
          PostDataByName(this.requestParam).then(response => {
            this.$nextTick(() => {
              this.$refs['temp'].clearValidate()
            })
            if (response.msg !== 'fail') {
              this.get_table_data()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },
    // 设备开始
    eq_popoverHide(checkedIds, checkedData) {
      this.eq_dataform.selectedeq = checkedIds
      this.selectedeq = checkedIds
      this.UpdateDataRelationParam.values = checkedIds
    },
    geteqList() {
      GetDataByName(this.getEQParm).then(response => {
        if (response.data.list !== null) {
          this.parenteq = transData(response.data.list, 'id', 'pid', 'children')
        }
      })
    },
    handleeqMenu(row) {
      this.dialogeqVisible = true
      this.requestParam.name = 'getEQByBrand'
      this.requestParam.parammaps = { brandId: row.id }
      this.requestParam.pagecount = 0
      this.requestParam.returntype = 'list'
      this.dialogMenuVisible = true
      GetDataByName(this.requestParam).then(response => {
        this.selectedeq = response.data.lists.eqClassId
        this.eq_defaultCheckedKeys = this.selectedeq
        this.UpdateDataRelationParam.values = this.eq_defaultCheckedKeys
      })
    },
    updateeq() {
      this.UpdateDataRelationParam.name = 'brand_eqclass'
      this.UpdateDataRelationParam.dataname = 'brandId'
      this.UpdateDataRelationParam.datavalue = this.requestParam.parammaps.brandId
      this.UpdateDataRelationParam.valuename = 'eqClassId'
      this.UpdateDataRelationParam.values = this.selectedeq

      UpdateDataRelation(this.UpdateDataRelationParam).then(response => {
        if (response.msg !== 'fail') {
          this.dialogeqVisible = false
          this.get_table_data()
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
        } else {
          failproccess(response, this.$notify)
        }
      })
    },
    // 设备选择结束
    // 备件开始
    popoverHide(checkedIds, checkedData) {
      this.dataform.selectedstock = checkedIds
      this.selectedstock = checkedIds
      this.UpdateDataRelationParam.values = checkedIds
    },
    getStockList() {
      GetDataByName(this.getStockParm).then(response => {
        if (response.data.list !== null) {
          this.parentstock = transData(response.data.list, 'id', 'pid', 'children')
        }
      })
    },
    handlePartMenu(row) {
      this.dialogstockVisible = true
      this.requestParam.name = 'getByPartBrand'
      this.requestParam.parammaps = { brandId: row.id }
      this.requestParam.pagecount = 0
      this.requestParam.returntype = 'list'
      this.dialogMenuVisible = true
      GetDataByName(this.requestParam).then(response => {
        this.selectedstock = response.data.lists.partClassId
        this.defaultCheckedKeys = this.selectedstock
        this.UpdateDataRelationParam.values = this.defaultCheckedKeys
      })
    },
    updatestock() {
      this.UpdateDataRelationParam.name = 'brand_partclass'
      this.UpdateDataRelationParam.dataname = 'brandId'
      this.UpdateDataRelationParam.datavalue = this.requestParam.parammaps.brandId
      this.UpdateDataRelationParam.valuename = 'partClassId'
      this.UpdateDataRelationParam.values = this.selectedstock

      UpdateDataRelation(this.UpdateDataRelationParam).then(response => {
        if (response.msg !== 'fail') {
          this.dialogstockVisible = false
          this.get_table_data()
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
        } else {
          failproccess(response, this.$notify)
        }
      })
    },
    // 备件选择结束
    form_edit(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    edit_dialog_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'updateBrand'
          this.requestParam.parammaps = this.temp
          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.get_table_data()
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },
    form_delete(row) {
      MessageBox.confirm('品牌名称：' + row.brandName, '确认禁用？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deleteBrand'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.id = row.id
        PostDataByName(this.requestParam).then(response => {
          if (response.msg !== 'fail') {
            this.get_table_data()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消禁用'
          })
        })
    },

    // 导出
    handleDownload() {
      this.$alert('品牌正在导出中，请勿刷新或离开本页面，若导出时间过长，建议缩小导出数据范围重新导出', {})
      this.isPercentage = true
      this.percentage = 1
      var timer = setInterval(() => {
        this.percentage += 5
        if (this.percentage > 95) {
          this.percentage = 99
          clearInterval(timer)
        }
        this.percentage = this.percentage
      }, 1000)
      this.requestParam.name = 'getBrandList'
      GetAccount(this.requestParam).then(response => {
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            if (response.data.list !== '') {
              this.percentage = 99
              setTimeout(() => {
                this.isPercentage = false
              }, 2000)
            }
            const tHeader = [
              '品牌名称', '资产数', '备件数', '合同数', '设备类型数', '启用'
            ]
            const filterVal = [
              'brandName', 'eqs', 'prs', 'cts', 'bps', 'enable'
            ]
            const data1 = formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '品牌',
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },

    handleEnableChange(index, row) { // 启用按钮更新状态
      this.requestParam.name = 'updateBrandEnable' // 接口名称
      this.requestParam.parammaps = {}
      this.requestParam.parammaps.enable = row.enable // 传递参数
      this.requestParam.parammaps.id = row.id

      PostDataByName(this.requestParam).then(response => { // 响应信息处理
        if (response.msg !== 'fail') {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
        } else {
          failproccess(response, this.$notify)
        }
      })
    }
  }
}
</script>
