<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- 搜索条件 -->
      <el-select v-model="getdataListParm.parammaps.pastureName" placeholder="牧场" class="filter-item" style="width: 140px;">
        <el-option v-for="item in findAllPasture" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-input v-model="getdataListParm.parammaps.partCode" placeholder="备件编号" style="width: 140px;" class="filter-item" />
      <el-input v-model="getdataListParm.parammaps.partName" placeholder="备件名称" style="width: 140px;" class="filter-item" />
      <el-select v-model="getdataListParm.parammaps.listType" clearable placeholder="清单类型" class="filter-item">
        <el-option v-for="item in findAllListType" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="getdataListParm.parammaps.statue" clearable placeholder="处理状态" class="filter-item" style="width: 140px;">
        <el-option v-for="item in findAllStatus" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-date-picker ref="inputDatetime" v-model="getdataListParm.parammaps.inputDatetime" class="inputDatetime" type="datetimerange" style="width: 250px;top:-3px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</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="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.repairCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="清单类型" min-width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.listType == 0?"维修":"保养" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pastureName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" min-width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.departName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备件编号" min-width="130px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.partCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备件名称" min-width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.partName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备件规格" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.specification }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联设备名称" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.eqName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备内部编号" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.eqCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" sortable prop="amount" min-width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" min-width="80px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.statue == 0">未处理</span>
          <span v-if="scope.row.statue == 1">已卖掉</span>
          <span v-if="scope.row.statue == 2">已销毁</span>
          <span v-if="scope.row.statue == 3">已修复</span>
        </template>
      </el-table-column>
      <el-table-column label="处理价格" sortable prop="saleSum" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.saleSum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理日期" sortable prop="handleDate" min-width="90px" align="center" />
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="form_see(row)">查看</el-button>
          <el-button v-if="row.statue == 0" type="success" size="mini" @click="handleDestruction(row)">处理</el-button>
          <!-- <el-button v-if="isOld" type="success" size="mini" @click="handleDestruction(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" />
    <!-- 弹出层销毁/卖掉 -->
    <el-dialog title="旧品处理" :visible.sync="dialogFormVisibleDestruction" :close-on-click-modal="false" width="30%">
      <el-form ref="temp" :model="temp" label-position="right" label-width="100px" style="width: 400px;" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="处理方式:" prop="radio" style="width:400px">
              <el-radio-group v-model="isOrNo">
                <el-radio v-model="isOrNo" label="0">销毁</el-radio>
                <el-radio v-model="isOrNo" label="1">卖掉</el-radio>
                <el-radio v-model="isOrNo" label="2">修复</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isOrNo == 1">
          <el-col :span="12">
            <el-form-item label="卖出总价：" prop="saleSum">
              <el-input
                v-model="temp.saleSum"
                placeholder="卖出总价"
                style="width: 250px;"
                class="filter-item"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isOrNo == 2">
          <el-col :span="12">
            <el-form-item label="修复价格:" prop="saleSum">
              <el-input v-model="temp.saleSum" placeholder="修复价格" style="width: 250px;" class="filter-item" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处理人：" prop="employeId">
              <el-select
                v-model="temp.employeId"
                placeholder="处理人"
                class="filter-item"
                style="width:250px;"
              >
                <el-option
                  v-for="item in findAllEmploye"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处理日期：" prop="date">
              <el-date-picker
                v-model="temp.date"
                type="date"
                placeholder="日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"

                style="width:250px;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="edit_dialog_saveDestruction()"
        >确认</el-button>
        <el-button @click="dialogFormVisibleDestruction = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 记录 -->
    <el-dialog title="查看详情" :visible.sync="dialogFormVisibleCard" :close-on-click-modal="false" width="90%">
      <div class="app-contentcard">
        <el-form ref="rowSeeData" :model="rowSeeData" label-position="right" label-width="120px" style="width: 100%;margin:0 auto;">
          <div class="filter-container">

            <el-row>
              <el-col :span="6">
                <el-form-item label="清单编号：" prop="repairCode">
                  <el-input v-model="rowSeeData.repairCode" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="清单类型：" prop="listType">
                  <el-input v-model="rowSeeData.listType == 0 ? '维修':'保养' " placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="牧场：" prop="pastureName">
                  <el-input v-model="rowSeeData.pastureName" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="部门：" prop="departName">
                  <el-input v-model="rowSeeData.departName" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>

              <el-col :span="6">
                <el-form-item label="备件编号：" prop="partCode">
                  <el-input v-model="rowSeeData.partCode" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="备件名称：" prop="partName">
                  <el-input v-model="rowSeeData.partName" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="备件规格：" prop="specification">
                  <el-input v-model="rowSeeData.specification" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="关联设备名称：" prop="eqName">
                  <el-input v-model="rowSeeData.eqName" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>

              <el-col :span="6">
                <el-form-item label="设备内部编号：" prop="eqCode">
                  <el-input v-model="rowSeeData.eqCode" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="数量：" prop="amount">
                  <el-input v-model="rowSeeData.amount" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="处理状态：" prop="statue">
                  <el-input v-if="rowSeeData.statue == 0" value="未处理" placeholder="" style="width: 100%;" class="filter-item" disabled />
                  <el-input v-if="rowSeeData.statue == 1" value="已卖掉" placeholder="" style="width: 100%;" class="filter-item" disabled />
                  <el-input v-if="rowSeeData.statue == 2" value="已销毁" placeholder="" style="width: 100%;" class="filter-item" disabled />
                  <el-input v-if="rowSeeData.statue == 3" value="已修复" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item v-if="rowSeeData.statue == 1" label="卖出总价：" prop="saleSum">
                  <el-input v-model="rowSeeData.saleSum" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
                <el-form-item v-if="rowSeeData.statue == 3" label="修复总价：" prop="saleSum">
                  <el-input v-model="rowSeeData.saleSum" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>

              <el-col :span="6">
                <el-form-item label="处理日期：" prop="handleDate">
                  <el-input v-model="rowSeeData.handleDate" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="处理人：" prop="handlerName">
                  <el-input v-model="rowSeeData.handlerName" placeholder="" style="width: 100%;" class="filter-item" disabled />
                </el-form-item>
              </el-col>

            </el-row>

          </div>
        </el-form>
        <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom:10px">
          <el-button @click="dialogFormVisibleCard = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
import { GetDataByName, GetDataByNames, PostDataByName, checkButtons } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime, sortChange } from '@/utils/index.js'
import { validateEMail } from '@/utils/validate.js'
import Pagination from '@/components/Pagination'
import Cookies from 'js-cookie'
export default {
  name: 'Refuse',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      myHeight:document.documentElement.clientHeight - 85- 200,
      isOld: [],
      isOrNo: '0',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      state1: '',
      radio: '',
      requestParam: {
        name: 'insertAsset',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      // 1-2:table&搜索传参
      getdataListParm: {
        name: 'getRefuseList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          inputDatetime: new Date(),
          pastureName: Cookies.get('pasturename'),
          partCode: '',
          partName: '',
          listType: '',
          statue: '',
          startTime: '',
          stopTime: ''
        }
      },
      // 2-3：下拉框请求后数据加入[]
      findAllListType: [
        { id: 0, name: '维修' },
        { id: 1, name: '保养' }],
      findAllStatus: [
        { id: 0, name: '未处理' },
        { id: 1, name: '已卖掉' },
        { id: 2, name: '已销毁' },
        { id: 3, name: '已修复' }
      ],
      findAllProvider: [],
      findAllAssetType: [],
      findAllPasture: [],
      findAllDepart: [],
      findAllEmploye: [],
      getDictByName: [],
      // 2-1.请求下拉框接口
      requestParams: [
        { name: 'findAllProvider', offset: 0, pagecount: 0, params: [] },
        { name: 'findAllAssetType', offset: 0, pagecount: 0, params: [] },
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }},
        { name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }},
        { name: 'findAllEmploye', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }},
        { name: 'getDictByName', offset: 0, pagecount: 0, params: ['旧品状态'] }
      ],

      temp: {
        date: parseTime(new Date(), '{y}-{m}-{d}'),
        employeId: this.$store.state.user.employeid,
        departmentId: this.$store.state.user.departmentid,
        pastureId: this.$store.state.user.pastureid
      },
      dialogFormVisibleDestruction: false,
      dialogStatusDestruction: '',

      dialogPvVisible: false,
      // 校验规则
      rules: {
        // saleSum: [
        //   { required: true, message: '必填', trigger: 'blur' }
        // 引入自定义校验并使用
        // { validator: validateEMail, trigger: 'blur' }
        // ],

      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      dialogFormVisibleCard: false,
      rowSeeData: {},
      buttons: []

    }
  },
  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 Old = 'customs:receive:old'
      const isOld = checkButtons(this.$store.state.user.buttons, Old)
      this.isOld = isOld
    },
    changeStorageType(val) {
      console.log(val)
      if (val === 0) {

      } else {

      }
    },
    // 供应商模糊查询
    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
      if (this.$refs['inputDatetime'] !== undefined && this.$refs['inputDatetime'].value !== null) {
        this.getdataListParm.parammaps.startTime = this.$refs['inputDatetime'].value[0]
        this.getdataListParm.parammaps.stopTime = this.$refs['inputDatetime'].value[1]
      } else {
        this.getdataListParm.parammaps.startTime = ''
        this.getdataListParm.parammaps.stopTime = ''
      }
      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
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    // 2-2：下拉框
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllProvider = response.data.findAllProvider.list
        this.findAllAssetType = response.data.findAllAssetType.list
        this.findAllPasture = response.data.findAllPasture.list
        this.findAllDepart = response.data.findAllDepart.list
        this.findAllEmploye = response.data.findAllEmploye.list
        this.getDictByName = response.data.getDictByName.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_see(row) {
      console.log(row)
      this.rowSeeData = Object.assign({}, row)
      this.dialogFormVisibleCard = true
    },

    // 销毁/卖掉
    handleDestruction(row) {
      this.temp.id = row.id
      this.dialogFormVisibleDestruction = true
      // if (row.statue === '未处理') {
      //   console.log(row)
      //   this.temp = Object.assign({}, row) // copy obj
      //   this.dialogStatusDestruction = 'destruction'
      //   this.dialogFormVisibleDestruction = true
      // } else {
      //   this.$notify({
      //     title: '',
      //     message: '旧品已处理...',
      //     type: 'warning',
      //     duration: 2000
      //   })
      // }
    },
    edit_dialog_saveDestruction() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          console.log(this.temp)
          if (this.isOrNo == 0) {
            this.$confirm('是否销毁?', '提示', {
              confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', center: true
            }).then(() => {
              var send_data1 = {
                name: 'handleRefuseXH',
                parammaps: { id: this.temp.id, empId: this.temp.employeId, handleDate: this.temp.date }
              }

              PostDataByName(send_data1).then(response => {
                console.log(response)
                if (response.msg === 'fail') {
                  this.$notify({ title: '失败', message: '保存失败-' + response.data, type: 'warning', duration: 2000 })
                } else {
                  this.get_table_data()
                  this.dialogFormVisibleDestruction = false
                  this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
                }
              })
            }).catch(() => {
              this.$message({ type: 'info', message: '已取消' })
            })
          } else if (this.isOrNo == 1) {
            console.log(this.temp.saleSum)
            if (this.temp.saleSum == '' || this.temp.saleSum == undefined) {
              this.$message('未输入价格！')
            } else {
              this.$confirm('是否卖掉?', '提示', {
                confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', center: true
              }).then(() => {
                var send_data2 = {
                  name: 'handleRefuseMC',
                  parammaps: { id: this.temp.id, saleSum: this.temp.saleSum, empId: this.temp.employeId, handleDate: this.temp.date }
                }

                PostDataByName(send_data2).then(response => {
                  console.log(response)
                  if (response.msg === 'fail') {
                    this.$notify({ title: '失败', message: '保存失败-' + response.data, type: 'warning', duration: 2000 })
                  } else {
                    this.get_table_data()
                    this.dialogFormVisibleDestruction = false
                    this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
                  }
                })
              }).catch(() => {
                this.$message({ type: 'info', message: '已取消' })
              })
            }
          } else if (this.isOrNo == 2) {
            if (this.temp.saleSum == '' || this.temp.saleSum == undefined) {
              this.$message('未输入价格！')
            } else {
              this.$confirm('是否修复?', '提示', {
                confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', center: true
              }).then(() => {
                var send_data3 = {
                  name: 'handleRefuseXF',
                  parammaps: { id: this.temp.id, saleSum: this.temp.saleSum, empId: this.temp.employeId, handleDate: this.temp.date }
                }

                PostDataByName(send_data3).then(response => {
                  console.log(response)
                  if (response.msg === 'fail') {
                    this.$notify({ title: '失败', message: '保存失败-' + response.data, type: 'warning', duration: 2000 })
                  } else {
                    this.get_table_data()
                    this.dialogFormVisibleDestruction = false
                    this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
                  }
                })
              }).catch(() => {
                this.$message({ type: 'info', message: '已取消' })
              })
            }
          }
        }
      })
    }
  }
}
</script>
