<template>
  <div class="app-container">
    <div class="tab-header webtop">
      <div>{{ title }}旧件处理申请</div>
      <div>
        <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate">保存</el-button>
        <el-button type="primary" size="small" :disabled="submitdisabled" @click="submit">提交</el-button>
        <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
      </div>
    </div>
    <div class="listconadd">
      <el-form ref="form_obj" :model="formobj" :rules="rules" class="formaddcopy02">
        <el-row class="first_row">
          <el-col :span="8">
            <div class="span-sty">申请人</div>
            <el-form-item><span class="addinputInfo">{{ formobj.createByName }}</span></el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">申请部门</div>
            <el-form-item><span class="addinputInfo">{{ formobj.deptName }}</span></el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">申请日期</div>
            <el-form-item><span class="addinputInfo">{{ formobj.createTime }}</span></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <div class="span-sty"><span class="must">*</span> 处理原因</div>
            <el-form-item prop="handleReasonValue">
              <el-select v-model="formobj.handleReasonValue" placeholder="请选择" class="addinputw addinputInfo" @change="selectHandleReason">
                <el-option v-for="item in reasonList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty"><span class="must">*</span> 处理方式</div>
            <el-form-item prop="handleModeValue">
              <el-select v-model="formobj.handleModeValue" placeholder="请选择" class="addinputw addinputInfo" @change="selectHandleMode">
                <el-option v-for="item in modeList" :key="item.dictKey" :label="item.dictValue" :value="item.item.dictKey">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">收益总额</div>
            <el-form-item><span class="addinputInfo">{{ totalQuantity }}</span></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="span-sty">备注</div>
            <el-form-item>
              <el-input v-model="formobj.remarks" placeholder="" class="addinputw addinputInfo" type="textarea" :rows="4" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="span-sty"><span class="must">*</span> 附件</div>
            <el-form-item prop="imgList">
              <upload-img ref="uploadImg" class="addinputw" v-model="imgList" :limit="50" bucket="map" :upload-data="{ type: '0001' }" @change="backData"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title titleOne">
          <div>待处理旧件列表</div>
          <el-button type="primary" size="mini" @click="importDetail()">选择旧件</el-button>
        </div>
        <el-table v-loading="listLoading" :data="formobj.asOldparthandleList" border>
          <el-table-column fixed width="60" label="序号" type="index" :index="indexMethod" align="center"/>
          <el-table-column fixed label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="deleteAsOldparthandle(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="goodsID" label="商品ID" align="center"/>
          <el-table-column prop="goodsSpuName" label="商品名称" align="center"/>
          <el-table-column prop="goodsSkuCode" label="图号" align="center"/>
          <el-table-column prop="manufacturerName" label="厂家" align="center"/>
          <el-table-column prop="goodsSkuOwnSpec" label="规格" align="center"/>
          <el-table-column prop="unit" label="单位" align="center"/>
          <el-table-column prop="warehouseName" label="仓库" align="center"/>
          <el-table-column prop="warehouseRackCode" label="库位" align="center"/>
          <el-table-column label="数量" align="center" width="180">
            <template slot-scope="scope">
              <el-input ref="focusAssumptionInput" v-model="scope.row.count" clearable placeholder="" @input="commodityComputeYHAndXSJE(scope.row)" oninput="value=value.replace(/^(0+)|[^\d]+/g,'')"/>
            </template>
          </el-table-column>
          <el-table-column prop="profit" label="收益金额" align="center"/>
        </el-table>
      </el-form>
    </div>
    <el-dialog title="选择旧件商品" :visible.sync="dialogVisible" :before-close="handleClose" style="width:150%;margin-left: -20%;">
      <el-form :inline="true" class="tab-header" style="margin-top: -30px;">
        <el-form-item label="商品ID">
          <el-input v-model="queryParams.params.goodsId" placeholder="" clearable/>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.params.goodsName" placeholder="" clearable/>
        </el-form-item>
        <el-form-item label="商品编码">
          <el-input v-model="queryParams.params.goodsSkuCode" placeholder="" clearable/>
        </el-form-item>
        <el-form-item label="厂家">
          <el-input v-model="queryParams.params.manufacturerName" placeholder="" clearable/>
        </el-form-item>
      </el-form>
      <div class="btn" style="text-align: center; margin-top: 20px;">
        <el-button type="primary" size="small" icon="el-icon-search" @click="dosearch">查询</el-button>
        <el-button type="primary" size="small" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </div>
      <el-table v-loading="tableLoading" :data="dataList" border style="width: 100%;margin-top: 20px;" @selection-change="selectionLineChangeHandle">
        <el-table-column fixed width="50" type="selection" align="center"/>
        <el-table-column fixed width="60" label="序号" type="index" :index="indexMethod" align="center"/>
        <el-table-column prop="goodsID" label="商品ID" align="center"/>
        <el-table-column prop="goodsSpuName" label="商品名称" align="center"/>
        <el-table-column prop="goodsSkuCode" label="商品编码" align="center"/>
        <el-table-column prop="goodsSkuOwnSpec" label="规格" align="center"/>
        <el-table-column prop="unit" label="单位" align="center"/>
        <el-table-column prop="manufacturerName" label="厂家" align="center"/>
        <el-table-column prop="vinNo" label="车架号" align="center"/>
        <el-table-column prop="sourceBillNo" label="维修单号" align="center"/>
        <el-table-column prop="count" label="库存数量" align="center"/>
      </el-table>
      <div class="pages">
        <div class="tit"/>
        <!--  翻页  -->
        <pagination v-show="dataList.length > 0" :total="queryParams.total" :page.sync="queryParams.current" :limit.sync="queryParams.size" class="pagination" @pagination="importDetail"/>
      </div>
      <div class="btn" style="text-align: center; margin-top: 20px;">
        <el-button type="primary" size="mini" @click="addDialogList()">确认</el-button>
        <el-button type="primary" size="mini" @click="handleClose()">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import req from '@/api/storage/oldPartsCope.js'
import uploadImg from '@/components/uploadFile/uploadImg'
import { getOrgSidByPath, typeValues } from '@/api/Common/dictcommons'
import { getCurrentDate } from '@/utils/index.js'
import Pagination from '@/components/pagination'

export default {
  components: {
    Pagination,
    uploadImg
  },
  data() {
    return {
      dialogVisible: false,
      title: '【新增】',
      tableLoading: false,
      loadList: false,
      listLoading: false,
      submitdisabled: false,
      formobj: {
        sid: '',
        remarks: '',
        createBySid: window.sessionStorage.getItem('userSid'),
        createByName: window.sessionStorage.getItem('name'),
        deptSid: window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1),
        deptName: window.sessionStorage.getItem('defaultOrgPathName').substring(window.sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1),
        createTime: getCurrentDate(),
        billNo: '',
        filePaths: [],
        useOrgSid: '',
        useOrgName: '',
        procDefId: '',
        nodeId: '',
        procInstId: '',
        nodeState: '',
        taskId: '',
        finishTime: '',
        totalProfit: '',
        asOldparthandleList: []
      },
      imgList: [],
      modeList: [],
      reasonList: [],
      selectionList: [],
      queryParams: {
        current: 1,
        size: 10,
        total: 0,
        params: {
          goodsName: '',
          goodsSkuCode: '',
          warehouseName: '',
          warehouseRackCode: '',
          supplierName: ''
        }
      },
      dataList: [],
      rules: {
        handleReasonValue: [{ required: true, message: '处理原因不能为空', trigger: 'change' }],
        handleModeValue: [{ required: true, message: '处理方式不能为空', trigger: 'change' }],
        filePaths: [{ required: true, message: '附件不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 收益总额
    totalQuantity() {
      let quantity = 0
      if (this.formobj.asOldparthandleList.length > 0) {
        this.formobj.asOldparthandleList.forEach((e) => {
          quantity += Number(e.profit)
        })
      }
      return quantity
    }
  },
  created() {
    getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
      if (res.success) {
        this.formobj.createOrgSid = res.data
        this.formobj.useOrgSid = res.data
      }
    })
  },
  methods: {
    init() {
      typeValues({ type: 'process_mode' }).then((res) => {
        if (res.success) {
          this.modeList = res.data
        }
      })
      typeValues({ type: 'process_reason' }).then((res) => {
        if (res.success) {
          this.reasonList = res.data
        }
      })
    },
    selectHandleReason(val) {
      const choose = this.reasonList.filter((item) => item.dictKey === val)
      if (choose !== null && choose.length > 0) {
        this.formobj.handleReasonValue = choose[0].dictValue
        this.formobj.handleReasonKey = choose[0].dictKey
      } else {
        this.formobj.handleReasonValue = ''
        this.formobj.handleReasonKey = ''
      }
    },
    selectHandleMode(val) {
      const choose = this.modeList.filter((item) => item.dictKey === val)
      if (choose !== null && choose.length > 0) {
        this.formobj.handleModeValue = choose[0].dictValue
        this.formobj.handleModeKey = choose[0].dictKey
      } else {
        this.formobj.handleModeValue = ''
        this.formobj.handleModeKey = ''
      }
    },
    indexMethod(index) {
      return Number(index) + 1
    },
    dosearch() {
      this.queryParams.current = 1
      this.importDetail()
    },
    resetQuery() {
      this.queryParams = {
        current: 1,
        size: 10,
        total: 0,
        params: {
          goodsName: '',
          goodsSkuCode: '',
          warehouseName: '',
          warehouseRackCode: '',
          supplierName: ''
        }
      }
      this.importDetail()
    },
    importDetail() {
      this.tableLoading = true
      this.queryParams.params.userSid = window.sessionStorage.getItem('userSid')
      this.queryParams.params.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      this.queryParams.params.menuUrl = this.$route.path
      req.handleGoodsListPage(this.queryParams).then((resp) => {
        this.tableLoading = false
        this.dialogVisible = true
        if (resp.success) {
          const data = resp.data
          this.queryParams.total = data.total
          this.dataList = data.records
        } else {
          // 根据resp.code进行异常情况处理
          this.dataList = []
          this.queryParams.total = 0
        }
      }).catch(() => {
        this.tableLoading = false
      })
    },
    selectionLineChangeHandle(val) {
      this.selectionList = val
    },
    addDialogList() {
      for (var i = 0; i < this.selectionList.length; i++) {
        var item = {
          count: this.selectionList[i].count,
          goodsSkuCode: this.selectionList[i].goodsSkuCode,
          goodsID: this.selectionList[i].goodsID,
          goodsSpuSid: this.selectionList[i].goodsSpuSid,
          goodsSkuSid: this.selectionList[i].goodsSkuSid,
          goodsSpuName: this.selectionList[i].goodsSpuName,
          goodsSkuTitle: this.selectionList[i].goodsSkuTitle,
          goodsSkuOwnSpec: this.selectionList[i].goodsSkuOwnSpec,
          mainSid: '',
          sid: '',
          unit: this.selectionList[i].unit,
          vinNo: this.selectionList[i].vinNo,
          warehouseName: this.selectionList[i].warehouseName,
          warehouseRackCode: this.selectionList[i].warehouseRackCode,
          warehouseRackSid: this.selectionList[i].warehouseRackSid,
          warehouseSid: this.selectionList[i].warehouseSid,
          price: this.selectionList[i].price,
          sourceBillNo: this.selectionList[i].sourceBillNo,
          manufacturerSid: this.selectionList[i].manufacturerSid,
          manufacturerName: this.selectionList[i].manufacturerName,
          supplierSid: this.selectionList[i].supplierSid,
          supplierName: this.selectionList[i].supplierName,
          profit: (Number(this.selectionList[i].count) * Number(this.selectionList[i].price)).toFixed(2)
        }
        this.formobj.asOldparthandleList.push(item)
      }
      this.dialogVisible = false
    },
    handleClose() {
      this.dialogVisible = false
    },
    deleteAsOldparthandle(index) {
      this.formobj.asOldparthandleList.splice(index, 1)
    },
    saveOrUpdate() {
      this.formobj.totalProfit = this.totalQuantity
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.save(this.formobj).then((res) => {
            if (res.success) {
              this.$message({
                showClose: true,
                type: 'success',
                message: '保存成功'
              })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    submit() {
      this.formobj.totalProfit = this.totalQuantity
      if (this.formobj.asOldparthandleList.length === 0) {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '旧件申请列表不能为空'
        })
        return
      }
      for (var i = 0; i < this.formobj.asOldparthandleList.length; i++) {
        if (Number(this.formobj.asOldparthandleList[i].count) === 0) {
          this.$message({
            showClose: true,
            type: 'warning',
            message: '旧件数量不能为空'
          })
          return
        }
      }
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.submit(this.formobj).then((res) => {
            if (res.success) {
              this.$message({
                showClose: true,
                type: 'success',
                message: '保存成功'
              })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.imgList = []
      this.formobj = {
        sid: '',
        remarks: '',
        createBySid: window.sessionStorage.getItem('userSid'),
        createByName: window.sessionStorage.getItem('name'),
        deptSid: window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1),
        deptName: window.sessionStorage.getItem('defaultOrgPathName').substring(window.sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1),
        createTime: getCurrentDate(),
        billNo: '',
        filePaths: [],
        useOrgSid: '',
        useOrgName: '',
        procDefId: '',
        nodeId: '',
        procInstId: '',
        nodeState: '',
        taskId: '',
        finishTime: '',
        totalProfit: '',
        asOldparthandleList: []
      }
      this.submitdisabled = false
      this.$emit('doback')
    },
    showAdd() {
      this.title = '【新增】'
      this.init()
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
    },
    showEdit(row) {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.title = '【修改】'
      this.init()
      req.init(row.sid).then(resp => {
        if (resp.success) {
          this.formobj = resp.data
          for (var i = 0; i < resp.data.filePaths.length; i++) {
            this.imgList.push({
              url: resp.data.filePaths[i].url
            })
          }
        }
      }).catch(e => {
        this.formobj = {}
      })
    },
    backData(value) {
      this.formobj.filePaths = []
      if (this.imgList.length > 0) {
        for (var i = 0; i < this.imgList.length; i++) {
          this.formobj.filePaths.push(this.imgList[i].url)
        }
      }
    },
    commodityComputeYHAndXSJE(row) {
      row.profit = (Number(row.count) * Number(row.price)).toFixed(2)
    }
  }
}
</script>
<style scoped>
/deep/ .el-form-item__error {
  margin-left: 120px !important;
}

.must {
  color: #f00;
}

.span-sty {
  width: 130px !important;
}

.addinputInfo {
  margin-left: 120px !important;
}

.formaddcopy02 .el-row .el-col /deep/ .el-form-item .addinputw {
  margin-left: 120px !important;
  width: calc(100% - 115px);
}

.first_row {
  border-top: 1px solid #E0E3EB;
}

.titleOne {
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</style>
