<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="table1.getdataListParm.parammaps.writeoffType" style="width: 140px;" placeholder="冲销类型" class="filter-item" @change="change_type">
        <el-option v-for="item in writeoffList" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-input  v-model="table1.getdataListParm.parammaps.orderNumber" placeholder="设备管理平台单号" style="width: 200px;" class="filter-item" />
       <!-- <el-input v-if="table1.getdataListParm.parammaps.writeoffType == '备件入库'" v-model="table1.getdataListParm.parammaps.orderNumber" placeholder="入库单号" style="width: 200px;" class="filter-item" />
      <el-input v-if="table1.getdataListParm.parammaps.writeoffType == '备件出库'" v-model="table1.getdataListParm.parammaps.orderNumber" placeholder="出库单号" style="width: 200px;" class="filter-item" />
      <el-input v-if="table1.getdataListParm.parammaps.writeoffType == '备件退库'" v-model="table1.getdataListParm.parammaps.orderNumber" placeholder="退库单号" style="width: 200px;" class="filter-item" />
      <el-input v-if="table1.getdataListParm.parammaps.writeoffType == '备件退货'" v-model="table1.getdataListParm.parammaps.orderNumber" placeholder="退货单号" style="width: 200px;" class="filter-item" />  -->
      <el-select v-model="table1.getdataListParm.parammaps.hasTicket" style="width: 180px;" clearable placeholder="是否已开票" class="filter-item" v-if="table1.getdataListParm.parammaps.writeoffType == '备件入库' || table1.getdataListParm.parammaps.writeoffType == '备件退货'">
        <el-option v-for="item in invoicedReturnDocList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <div>
        <el-button v-if="isWriteoffAdd" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">新增</el-button>
      </div>
    </div>
    <el-table
      :key="table1.tableKey"
      v-loading="table1.listLoading"
      element-loading-text="给我一点时间"
      :data="table1.list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      class="elTable"
    >
      <el-table-column label="序号" align="center" type="index" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + (table1.pageNum-1) * table1.pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物料凭证号" min-width="150px" align="center" prop="materialCode" />
      <el-table-column label="物料凭证年度" min-width="150px" align="center" prop="proofYear" />
      <el-table-column label="凭证中的过账信息" min-width="150px" align="center" prop="chargeDate" />
      <el-table-column label="设备管理平台单号" min-width="150px" align="center" prop="orderNumber" />
 
      <el-table-column label="是否已开票" min-width="150px" align="center" show-overflow-tooltip v-if="table1.getdataListParm.parammaps.writeoffType == '备件入库' || table1.getdataListParm.parammaps.writeoffType == '备件退货'" >
            <template slot-scope="scope">
              <span v-if="scope.row.hasTicket == 1">是</span>
              <span v-if="scope.row.hasTicket == 0">否</span>
              <span v-if="scope.row.hasTicket == ''"> </span>
            </template>
          </el-table-column>
      <el-table-column label="设备管理平台行号" min-width="150px" align="center" prop="rowNumber" />
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button v-if="isWriteoffSee" type="primary" size="mini" @click="handleSee(row)">查看</el-button>
          <!-- <el-button v-if="isWriteoffDel" type="danger" size="mini" @click="handleDelate(row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="table1.total>0" :total="table1.total" :page.sync="table1.getdataListParm.offset" :limit.sync="table1.getdataListParm.pagecount" @pagination="getList" />
    <!-- 弹出层新增or修改 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="90%">
      <div class="app-container">
        <el-form ref="create" :rules="rules" :model="create.temp" label-position="right" label-width="140px" style="width: 90%;margin:0 auto;">
          <el-row>
            <el-col :span="8">
              <el-form-item label="设备管理平台单号:" prop="orderNumber">
                <el-input ref="orderNumber" v-model="create.temp.orderNumber" :disabled="dialogStatus=='see'" @blur="blurOrderNumber" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="冲销类型:" prop="NumberType">
                <el-select v-model="create.temp.NumberType" :disabled="dialogStatus=='see'" placeholder="" class="filter-item" style="width:100%" @change="changeWriteoff">
                  <el-option v-for="item in writeoffList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否已开票:" prop="hasTicket">
                <el-select v-model="create.temp.hasTicket" :disabled="dialogStatus=='see'" placeholder="" class="filter-item" style="width:100%">
                  <el-option v-for="item in invoicedReturnDocList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="物料凭证号:" prop="materialCode">
                <el-select v-model="create.temp.materialCode" disabled placeholder="" class="filter-item" style="width:100%">
                  <el-option v-for="item in materialVoucherNoList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="凭证中的过账日期:" prop="chargeDate">
                <el-date-picker v-model="create.temp.chargeDate" disabled :picker-options="pickerOptions" type="date" placeholder="" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料凭证年度:" prop="proofYear">
                <el-input ref="proofYear" v-model="create.temp.proofYear" disabled  placeholder="" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table
          :key="create.tableKey"
          v-loading="create.listLoading"
          element-loading-text="给我一点时间"
          :data="create.list"
          border
          fit
          highlight-current-row
          style="width: 100%;margin-bottom:30px"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable"
           @selection-change="handleSelectionChange"
          >
          <el-table-column type="selection"  width="55" />
          <el-table-column label="行号" align="center" prop="rowNumber" width="50px" />
          <el-table-column label="备件编号" prop="partCode" align="center" min-width="90" />
          <el-table-column label="备件名称" prop="partName" align="center" min-width="90" />
          <el-table-column label="备件规格" prop="specification" align="center" min-width="90" />
          <el-table-column label="备件品牌" prop="partBrand" align="center" min-width="90" />
          <el-table-column label="供应商" prop="supplier" align="center" min-width="90" />
          <el-table-column label="库位" prop="warehouse" align="center" min-width="90" />
          <el-table-column label="变更数量" prop="changeCount" align="center" min-width="90" />
          <el-table-column label="单价" prop="unitPrice" align="center" min-width="90" />
          <el-table-column label="总价" prop="totalPrice" align="center" min-width="90" />
        </el-table>
        <div slot="footer" class="dialog-footer" style="bottom:10px">
          <el-button type="primary" v-if="dialogStatus=='create'" :disabled="isokDisable" @click="createData()">保存并关闭</el-button>
          <el-button @click="dialogFormVisible = false;getList()">取消并关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// / 引入
import { GetDataByName, GetDataByNames,postJson, PostDataByName, ExecDataByConfig, checkButtons, failproccess } from '@/api/common'
import { parseTime } from '@/utils/index.js'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
export default {
  name: 'Writeoff',
  components: { Pagination },
  data() {
    return {
      requestParams: [
        { name: 'findAllProvider', offset: 0, pagecount: 0, params: [] },
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }},
        { name: 'getPastureList', offset: 0, pagecount: 0, returntype: 'Map', parammaps: {}},
        { name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid'), 'eId': Cookies.get('employeid') }},
        { name: 'findAllEmploye', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }}
      ],
      writeoffList:[{id:1,name:'备件入库'},{id:2,name:'备件退货'},{id:3,name:'备件出库'},{id:4,name:'备件退库'}], //冲销类型
      invoicedReturnDocList:[{id:0,name:'否'},{id:1,name:'是'}],//是否已开票退货单
      materialVoucherNoList:[{id:0,name:'11111'},{id:1,name:'2222'}],//物料凭证号
      // table1:{
      //   getdataListParm: {
      //     name: 'getBigPartTransferList', page: 1, offset: 1, pagecount: 10, returntype: 'Map',
      //     parammaps: {
      //       pastureName: Cookies.get('pasturename'),
      //       writeoffType:'',
      //       OrderNumber:''
      //     }
      //   },
      //   tableKey: 0, listLoading: false, total: 0, list: [],pageNum:0, pageSize:0
      // },
      table1:{
        getdataListParm: {
          name: 'getLaidProofList', page: 1, offset: 1, pagecount: 10, returntype: 'Map',
          parammaps: {
            pastureName: Cookies.get('pasturename'),
            writeoffType:'备件入库',
            orderNumber:'',
            hasTicket:''
          }
        },
        tableKey: 0, listLoading: false, total: 0, list: [],pageNum:0, pageSize:0
      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: { create: '新增', see: '查看' },
      rules: {
        orderNumber: [{ required: true, message: '必填', trigger: 'blur' }],
        NumberType: [{ required: true, message: '必填', trigger: 'blur' }],
      },
      create: {
        temp:{ applyDate: parseTime(new Date(), '{y}-{m}-{d}')},
        getdataListParm: {
          name: 'getPartTransferbybigid',
          returntype: 'Map',
          parammaps: {}
        },
        getdataListParm2: {
          name: 'getPartlaidByBigid',
          returntype: 'Map',
          parammaps: {bigid:""}
        },
        tableKey: 0, listLoading: false, total: 0, list: [], pageNum:0, pageSize:0
      },
      isokDisable: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()// 当天之前的时间可选
        }
      },
      isWriteoffAdd:[],
      isWriteoffSee:[],
      isWriteoffDel:[]
    }
  },

  created() {
    const that = this
    GetDataByName({ 'name': 'getUserPCButtons', 'parammaps': { 'jwt_username': Cookies.get('name') }}).then(response => {
      that.buttons = response.data.list
      that.getButtons()
    })
    this.getDownList()
    this.getList()
  },

  methods: {
    getButtons() {
      // 新增
      const WriteoffAdd = 'customs:writeoff:add'
      const isWriteoffAdd = checkButtons(this.$store.state.user.buttons, WriteoffAdd)
      this.isWriteoffAdd= isWriteoffAdd
      // 查看
      const WriteoffSee = 'customs:writeoff:see'
      const isWriteoffSee = checkButtons(this.$store.state.user.buttons, WriteoffSee)
      this.isWriteoffSee = isWriteoffSee
      // 删除
      const WriteoffDel = 'customs:writeoff:del'
      const isWriteoffDel = checkButtons(this.$store.state.user.buttons, WriteoffDel)
      this.isWriteoffDel = isWriteoffDel
    },

    getList() {
      this.table1.listLoading = true
      GetDataByName(this.table1.getdataListParm).then(response => {
        if(response.data.list){
          console.log('table数据', response.data.list)
          this.table1.list = response.data.list
          this.table1.pageNum = response.data.pageNum
          this.table1.pageSize = response.data.pageSize
        }else{
          this.table1.list = []
          this.table1.pageNum = 0
          this.table1.pageSize = 0
        }
        if (response.data.total) {
          this.table1.total = response.data.total
        }
        setTimeout(() => {
          this.table1.listLoading = false
        }, 100)
      })
    },
    handleFilter() {
      console.log('点击了table搜索')
      this.table1.listLoading = true
      this.table1.getdataListParm.offset = 1
      this.getList()
    },
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.create.temp = {'materialCode':'','proofYear':'','chargeDate':'','orderNumber':'','hasTicket':'','orderNumberId':'','NumberType':'','rowsNumber':[]}
      this.create.list = []
    },
    changeWriteoff(item){
      this.getTableFormList()
    },
    blurOrderNumber(){
      this.getTableFormList()
    },
    getTableFormList(){
      let url = 'authdata/sap/proof/detail'
      let data = {
        OrderNumber:this.create.temp.orderNumber,
        NumberType:this.create.temp.NumberType
      }
      if(this.create.temp.orderNumber == ''){
        this.$message({ title: '', message: '设备管理平台单号不能为空', type: 'warning', duration: 2000 })
        return
      }
      if(this.create.temp.NumberType == ''){
        this.$message({ title: '', message: '冲销类型不能为空', type: 'warning', duration: 2000 })
        return
      }
      postJson(url,data).then(response => {
       console.log(response.msg,'response===')
       if(response.msg !== 'fail' ){
          if(response.data){
            this.create.temp = response.data
            this.create.temp.rowsNumber = []
            if(response.data.parts){
              this.create.list = response.data.parts
            }else{
              this.create.list = []
            }
          }else{
            this.create.list = []
            this.create.temp = {}
          }
       }else{
          this.$notify({ title: '失败', message: response.message, type: 'warning', duration: 2000 })
       }
      }).catch((res)=>{
        // this.$message({ title: '', message: re, type: 'warning', duration: 2000 })
      })
    },
    handleSelectionChange(val) {
      this.create.temp.rowsNumber = []
      for(let i=0;i<val.length;i++){
        this.create.temp.rowsNumber.push(val[i].rowNumber)
      }
      console.log(this.create.temp.rowsNumber)
    },
    createData() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['create'].validate(valid => {
        if (valid) {
          console.log('新增保存',this.create.temp.rowsNumber)
          let url = "authdata/sap/proof/off"
          let data = {
            materialCode:this.create.temp.materialCode,
            proofYear:this.create.temp.proofYear,
            chargeDate:this.create.temp.chargeDate,
            orderNumber:this.create.temp.orderNumber,
            hasTicket:this.create.temp.hasTicket,
            rowsNumber:this.create.temp.rowsNumber,//[]
            orderNumberId:this.create.temp.orderNumberId,
            NumberType:this.create.temp.NumberType

          }
          if(this.create.temp.rowsNumber.length == 0){
            this.$message({  message: '请选择需要冲销的备件', type: 'warning', duration: 2000 })
            return
          }
          postJson(url,data).then(response => {
            if(response.msg !== 'fail'){
              this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
              this.dialogFormVisible = false
            }else{
              this.$notify({ title: '失败', message: response.message, type: 'warning', duration: 2000 })
            }
          })
        }
      })
    },


    change_type(item) {
      console.log(item)
      if(item == "备件入库"){ 
        this.table1.getdataListParm.name = 'getLaidProofList'
        this.table1.getdataListParm.parammaps.writeoffType = '备件入库'
       }
      if(item == "备件出库"){ this.table1.getdataListParm.name = 'getReturnProofList'
      this.table1.getdataListParm.parammaps.writeoffType = '备件出库' 
    }
      if(item == "备件退库"){ this.table1.getdataListParm.name = 'getQuitProofList' 
      this.table1.getdataListParm.parammaps.writeoffType = '备件退库' 
    }
      if(item == "备件退货"){ this.table1.getdataListParm.name = 'getUseProofList' 
      this.table1.getdataListParm.parammaps.writeoffType = '备件退货' 
    }
    },

    // 查看
    handleSee(row) {
      this.dialogStatus = 'see'
      
      this.create.temp = Object.assign({}, row)
     
      console.log('row',row)


      // this.create.getdataListParm.parammaps.id = this.create.temp.id
      // {id:1,name:'备件入库'},{id:2,name:'备件退货'},{id:3,name:'备件出库'},{id:4,name:'备件退库'}
      if(row.NumberType == 1){
        this.create.getdataListParm2.name = 'getPartlaidByBigid'
      }
      if(row.NumberType == 4){
        this.create.getdataListParm2.name = 'getPartquitByBigid'
      }
      if(row.NumberType == 2){
        this.create.getdataListParm2.name = 'getPartrefundByBigid'
      }
      if(row.NumberType == 3){
        this.create.getdataListParm2.name = 'getPartuseByBigid'
      }

      this.create.getdataListParm2.parammaps.bigid = row.id
      this.getDialogList2()
      // this.getDialogList()
       this.dialogFormVisible = true
    },

    getDialogList2() {
      GetDataByName(this.create.getdataListParm2).then(response => {
        if(response.data.list){
          this.create.list = response.data.list
          this.create.pageNum = response.data.pageNum
          this.create.pageSize = response.data.pageSize
        }else{
          this.create.list = []
          this.create.pageNum = 0
          this.create.pageSize = 0
        }
        if (response.data.total) {
          this.create.total = response.data.total
        }
        setTimeout(() => {
          this.create.listLoading = false
        }, 100)
      })
    },
    getDialogList() {
      GetDataByName(this.create.getdataListParm).then(response => {
        if(response.data.list){
          this.create.list = response.data.list
          this.create.pageNum = response.data.pageNum
          this.create.pageSize = response.data.pageSize
        }else{
          this.create.list = []
          this.create.pageNum = 0
          this.create.pageSize = 0
        }
        if (response.data.total) {
          this.create.total = response.data.total
        }
        setTimeout(() => {
          this.create.listLoading = false
        }, 100)
      })
    },

    getDownList() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllProvider = response.data.findAllProvider.list
        this.findAllPasture = response.data.findAllPasture.list
        this.findAllPasture2 = response.data.getPastureList.list
        this.findAllDepart = response.data.findAllDepart.list
        this.findAllEmploye = response.data.findAllEmploye.list
      })
    },

    handleDelate(row){
      MessageBox.confirm('确认删除此条信息？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      console.log('删除')
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .pagination-container{
    display: block !important;
  }
</style>
<style lang="scss">
.el-step__head.is-success {
    color: #409EFF;
    border-color: #409EFF;
}
.el-step__title.is-success{
  color: #409EFF;
}
.el-step__head.is-process{
  color: #409EFF;
  border-color: #409EFF;
  .el-step__icon.is-text{
    background: #409EFF;
    color: #fff;
  }
}
.step-row{
  color: #000;
}
</style>
