<template>
  <div>
    <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="formReadOnly"
             label-width="100px" @submit.native.prevent>
      <el-divider content-position="left"><i class="el-icon-document"></i> 基础信息</el-divider>
      <el-row :gutter="26">
        <el-col :span="12">
          <el-form-item label="入库编号" prop="wareHouseNumber">
            <el-input placeholder="自动生成" v-model="inputForm.wareHouseNumber" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入库名称" prop="wareHouseName"
                        :rules="[{required: true, message: '入库名称不能为空', trigger: 'blur'}
                 ]">
            <el-input v-model="inputForm.wareHouseName" placeholder="请填写入库名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经办人" prop="handledBy">
            <el-input v-model="inputForm.handledBy" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经办人部门" prop="handledByOffice">
            <SelectTree
              :disabled="true"
              ref="officeTree"
              :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"

              :url="`/sys/office/treeData?type=2`"
              :value="inputForm.handledByOffice"
              :accordion="true"
              size="medium"
              @getValue="(value) => {inputForm.handledByOffice=value}"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入库时间" prop="wareHouseDate" :rules="[{required: true, message:'请选择入库时间', trigger:'blur'}]">
            <el-date-picker
              v-model="inputForm.wareHouseDate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采购编号" prop="purchaseNo"
                        :rules="[]">
            <el-input size="medium" :readonly="true" @focus="openContractForm()" v-model="inputForm.purchaseNo" placeholder="请选择采购编号">
              <el-button slot="append" icon="el-icon-search" @click="openContractForm()"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <!--<el-col :span="12">
          <el-form-item label="合同编号" prop="contractNo"
                        :rules="[]">
            <el-input size="medium" :readonly="true" @focus="openContractChooseForm()" v-model="inputForm.contractNo" placeholder="请选择采购编号">
              <el-button slot="append" icon="el-icon-search" @click="openContractChooseForm()"></el-button>
            </el-input>
          </el-form-item>
        </el-col>-->
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="inputForm.remarks"
                      type="textarea"
                      :rows="5"
                      maxlength="500"
                      placeholder="请输入简介"
                      show-word-limit>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left"><i class="el-icon-document"></i>
        <el-link v-if="this.commonJS.isNotEmpty(this.inputForm.purchaseNo)" :underline="false" @click="viewContract(inputForm.purchaseNo)">采购详情</el-link>
        <span v-else>采购详情</span>
      </el-divider>
      <el-row  :gutter="15" >
        <vxe-table
          border
          show-footer
          show-overflow
          :footer-method="footerMethod"
          ref="detailTable"
          class="vxe-table-element"
          :data="inputForm.detailInfos"
          style="margin-left: 5em"
          @cell-click=""
          @edit-closed=""
          highlight-current-row
          :edit-config="{trigger: 'click', mode: 'row', showStatus: false, autoClear: true, icon: '-'}"
        >
          <vxe-table-column field="purchaserAgent" title="采购人" :edit-render="{}" :rules="[{required: true, message:'请选择采购人', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input :disabled='true' v-model="scope.row.purchaserAgent"></el-input>
              <!--                <el-input v-model="scope.row.purchaser" @focus="userPullListForm(scope.$rowIndex)"></el-input>-->
            </template>
          </vxe-table-column>
          <vxe-table-column field="procurementOffice" title="采购部门" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input :disabled='true' v-model="scope.row.procurementOffice" ></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="procurementType" title="采购类型" :edit-render="{}" :rules="[{required: true, message:'请选择采购类型', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input :disabled='true' v-model="scope.row.procurementType"></el-input>
              <!--                <el-input v-model="scope.row.procurementType" @focus="typePullForm(scope.$rowIndex)"></el-input>-->
            </template>
          </vxe-table-column>
          <vxe-table-column field="tradeName" width="250" title="商品名称" :edit-render="{}" :rules="[{required: true, message:'请填写商品名称', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input :disabled='true' v-model="scope.row.tradeName"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="tradePrice" title="商品单价(元)" :edit-render="{}" :rules="[{required: true, message:'请输入商品单价', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <!--              <el-input @change="changeValue" maxlength="15" v-model="scope.row.tradePrice" @keyup.native="scope.row.tradePrice = twoDecimalPlaces(scope.row.tradePrice)"></el-input>-->
              <el-input :disabled='true' @change="changeValue" maxlength="15" v-model="scope.row.tradePrice"></el-input>
              <!--                <el-input @change="changeValue" maxlength="15" v-model="scope.row.tradePrice" @blur="scope.row.tradePrice = twoDecimalPlaces(scope.row.tradePrice)"></el-input>-->
            </template>
          </vxe-table-column>
          <vxe-table-column field="tradeNumber" title="商品数量" :edit-render="{}">
            <template v-slot:edit="scope">
              <!--              <el-input @change="changeValue" v-model="scope.row.tradeNumber" oninput ="value=value.replace(/\D|^0/g,'')" maxlength="10"></el-input>-->
              <el-input :disabled='true' @change="changeValue" v-model="scope.row.tradeNumber" maxlength="10"></el-input>
              <!--                <el-input @change="changeValue" v-model="scope.row.tradeNumber" @blur="scope.row.tradeNumber = twoDecimalPlaces2(scope.row.tradeNumber)" maxlength="10"></el-input>-->
            </template>
          </vxe-table-column>
          <vxe-table-column field="priceSum" title="商品总价" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input :disabled='true' v-model="scope.row.priceSum" maxlength="15"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="company" title="单位" :edit-render="{}" :rules="[{required: true, message:'请填写单位', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input :disabled='true' v-model="scope.row.company"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="remarks" title="备注" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input :disabled='true' v-model="scope.row.remarks" ></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column title="操作" width="180">
            <template v-slot="scope">
              <el-button size="mini" type="primary" :disabled="false" @click="seeFileInfo(scope.$rowIndex)">查看文件详情</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
      </el-row>
      <el-divider content-position="left"><i class="el-icon-document"></i>
        入库详情
        <el-button style="margin-left: 20px" type="primary" @click="insertEvent('detail')" plain>
          新增
        </el-button>
      </el-divider>
      <el-row  :gutter="15" >
        <vxe-table
          border
          show-footer
          show-overflow
          :footer-method="footerMethod2"
          ref="detailTable"
          class="vxe-table-element"
          :data="inputForm.wareHouse"
          style="margin-left: 5em"
          @cell-click=""
          @edit-closed=""
          highlight-current-row
          :edit-config="{trigger: 'click', mode: 'row', showStatus: false, autoClear: true, icon: '-'}"
          :edit-rules="validRules"
        >
          <vxe-table-column field="wareHouseMan" title="入库人" :edit-render="{}" :rules="[{required: true, message:'请选择入库人', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input v-model="scope.row.wareHouseMan" @focus="userPullListForm(scope.$rowIndex)"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="wareHouseManOffice" title="入库部门" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input :disabled='true' v-model="scope.row.wareHouseManOffice" ></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="wareHouseType" title="入库类型" :edit-render="{}" :rules="[{required: true, message:'请选择采购类型', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input v-model="scope.row.wareHouseType" @focus="typePullForm(scope.$rowIndex)"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="tradeName" width="250" title="商品名称" :edit-render="{}" :rules="[{required: true, message:'请填写商品名称', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input @change="ifSameValue" maxlength="64" v-model="scope.row.tradeName"></el-input>
            </template>
          </vxe-table-column>

          <vxe-table-column field="tradeNumber" title="商品数量" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input @change="changeValue2" v-model="scope.row.tradeNumber" @blur="scope.row.tradeNumber = twoDecimalPlaces2(scope.row.tradeNumber)" maxlength="10"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="company" title="单位" :edit-render="{}" :rules="[{required: true, message:'请填写单位', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input maxlength="64" v-model="scope.row.company"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="tradePrice" title="商品单价(元)" :edit-render="{}" :rules="[{required: true, message:'请输入商品单价', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input @change="changeValue2" maxlength="15" v-model="scope.row.tradePrice" @blur="scope.row.tradePrice = twoDecimalPlaces2(scope.row.tradePrice)"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="priceSum" title="商品总价" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input :disabled='true' v-model="scope.row.priceSum" @blur="scope.row.priceSum = twoDecimalPlaces(scope.row.priceSum)" maxlength="15"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="actualPrice" title="实际价格" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input v-model="scope.row.actualPrice" @blur="scope.row.actualPrice = twoDecimalPlaces(scope.row.actualPrice)" maxlength="15"></el-input>
            </template>
          </vxe-table-column>

          <vxe-table-column field="remarks" title="备注" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input maxlength="255" v-model="scope.row.remarks" ></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column title="操作" width="180">
            <template v-slot="scope">
              <el-button size="mini" type="danger" v-if="!formReadOnly" @click="removeEvent(scope.row,scope.$rowIndex,'detail')">删除</el-button>
              <el-button size="mini" type="primary" v-if="!formReadOnly" @click="sss2(scope.$rowIndex)">上传附件</el-button>
              <el-button size="mini" type="primary" v-if="formReadOnly" :disabled="false" @click="seeFileInfo2(scope.$rowIndex)">查看文件详情</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
      </el-row>
    </el-form>
    <!-- 附件 -->
    <MaterialManagementDialog ref="materialManagementDialog" @getUpload="getUpload"></MaterialManagementDialog>
    <UpdateInfoForm ref="updateInfoForm"></UpdateInfoForm>
    <PurchaseChooseForm  ref="purchaseChooseForm" @getProject="getContract"></PurchaseChooseForm>
    <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
    <CwProgramPageForm ref="cwProgramPageForm" @getProgram="getProgram"></CwProgramPageForm>
    <MaterialTypePullForm ref="materialTypePullForm" @getProgramForType="getProgramForType"></MaterialTypePullForm>
    <ContractChooseForm  ref="contractChooseForm" @getProject="getContract3"></ContractChooseForm>
    <UserPullForm ref="userPullForm" @getProgramForUser="getProgramForUser"></UserPullForm>
  </div>
</template>

<script>
  import MaterialManagementDialog from '../file/MaterialManagementDialog'
  import WareHouseService from '@/api/materialManagement/WareHouseService'
  import UpdateInfoForm from '../info/UpdateInfoForm'
  import PurchaseChooseForm from './PurchaseChooseForm'

  import UserSelect from '@/components/userSelect'
  import CommonApi from '@/api/cw/common/CommonApi'
  import MaterialManagementService from '@/api/materialManagement/MaterialManagementService'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import SelectUserTree from '@/views/modules/utils/treeUserSelect'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import XEUtils from 'xe-utils'
  import UserService from '@/api/sys/UserService'
  import CwProgramPageForm from '@/views/modules/cw/reimbursementApproval/info/CwProgramPageForm'
  import MaterialTypePullForm from '../info/MaterialTypePullForm'
  import UserPullForm from '@/views/modules/finance/invoice/UserPullForm'
  import ContractChooseForm from '../contract/ContractChooseForm'
  export default {
    data () {
      return {
        validRules: {
          wareHouseMan: [
            {required: true, message: '采购人不能为空'}
          ],
          wareHouseManOffice: [
            {required: true, message: '入库部门不能为空'}
          ],
          wareHouseType: [
            {required: true, message: '入库类型不能为空'}
          ],
          tradeName: [
            {required: true, message: '商品名称不能为空'}
          ],
          tradeNumber: [
            {required: true, message: '商品数量不能为空'}
          ]
        },
        title: '',
        method: '',
        visible: false,
        loading: false,
        indexRow: '',
        inputForm: {
          procInsId: '',
          wareHouseTotalPrice: '', // 入库商品总价
          wareHouseActualPrice: '', // 入库商品实际价格
          tradeTotalPrice: '',  // 商品总价
          fileInfoLost: [],
          purchaseNo: '',
          handledBy: '',
          handledById: '',
          handledByOffice: '',
          wareHouseName: '',
          wareHouseNumber: '', // 入库编号
          userId: '',
          wareHouseDate: '',
          remarks: '',
          detailInfos: [],
          wareHouse: [],
          // amountInfos: [],
          files: [] // 附件信息
        },
        keyWatch: ''
      }
    },
    WareHouseService: null,
    MaterialManagementService: null,
    userService: null,
    commonApi: null,
    created () {
      this.materialManagementService = new MaterialManagementService()
      this.userService = new UserService()
      this.commonApi = new CommonApi()
      this.wareHouseService = new WareHouseService()
    },
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    components: {
      MaterialManagementDialog,
      PurchaseChooseForm,
      UserSelect,
      UpLoadComponent,
      SelectUserTree,
      SelectTree,
      CwProgramPageForm,
      MaterialTypePullForm,
      UserPullForm,
      ContractChooseForm,
      UpdateInfoForm
    },
    computed: {
      bus: {
        get () {
          return this.businessId
        },
        set (val) {
          this.businessId = val
        }
      },
      name () {
        return JSON.parse(localStorage.getItem('user')).name
      },
      officeName () {
        return JSON.parse(localStorage.getItem('user')).officeDTO.name
      },
      purchaserAgentId () {
        return JSON.parse(localStorage.getItem('user')).id
      },
      procurementTypeId () {
        return ''
      }
    },
    watch: {
      'keyWatch': {
        handler (newVal) {
          if (this.commonJS.isNotEmpty(this.bus)) {
            this.init('', this.bus)
          } else {
            this.$nextTick(() => {
              this.$refs.inputForm.resetFields()
            })
          }
        }
      },
      'loading': {
        handler (newVal) {
          this.$emit('changeLoading', newVal)
          this.$refs.uploadComponent.changeLoading(newVal)
        }
      }
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      init (method, id) {
        this.method = method
        this.inputForm = {
          procInsId: '',
          wareHouseTotalPrice: '', // 入库商品总价
          wareHouseActualPrice: '', // 入库商品实际价格
          tradeTotalPrice: '',  // 商品总价
          fileInfoLost: [],
          purchaseNo: '',
          handledBy: JSON.parse(localStorage.getItem('user')).name,
          handledById: JSON.parse(localStorage.getItem('user')).id,
          handledByOffice: JSON.parse(localStorage.getItem('user')).officeDTO.id,
          wareHouseName: '',
          wareHouseNumber: '', // 入库编号
          userId: JSON.parse(localStorage.getItem('user')).id,
          wareHouseDate: new Date(),
          remarks: '',
          detailInfos: [],
          wareHouse: [],
          // amountInfos: [],
          files: [] // 附件信息
        }
        if (method === 'add') {
          this.title = `新建采购类型`
        } else if (method === 'edit') {
          this.title = '修改采购类型'
        }
        this.inputForm.id = id
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          if (this.formReadOnly === true && this.businessId !== 'false') {
            method = 'view'
          }
          if (this.commonJS.isEmpty(this.inputForm.handledByOffice)) {
            this.inputForm.handledByOffice = JSON.parse(localStorage.getItem('user')).officeDTO.id
          }
          if (this.status === 'audit' || this.status === 'taskFormDetail') {
            method = 'view'
          }
          this.loading = true
          this.$refs.inputForm.resetFields()
          this.wareHouseService.findById(this.inputForm.id).then(({data}) => {
            if (this.commonJS.isNotEmpty(data.wareHouseManId)) {
              this.wareHouseManId = data.wareHouseManId
            }
            if (this.commonJS.isNotEmpty(data.wareHouseTypeId)) {
              this.wareHouseTypeId = data.wareHouseTypeId
            }
            this.inputForm = this.recover(this.inputForm, data)
            if (this.commonJS.isEmpty(this.inputForm.handledByOffice)) {
              this.inputForm.handledByOffice = JSON.parse(localStorage.getItem('user')).officeDTO.id
            }
            let i = this.inputForm.detailInfos.length
            for (let j = 0; j < i; j++) {
              if (this.commonJS.isNotEmpty(this.inputForm.detailInfos[j].tradePrice)) {
                if (this.commonJS.isNotEmpty(this.inputForm.detailInfos[j].tradeNumber)) {
                  this.inputForm.detailInfos[j].priceSum = this.inputForm.detailInfos[j].tradePrice * this.inputForm.detailInfos[j].tradeNumber
                }
              }
            }
            let k = this.inputForm.wareHouse.length
            for (let j = 0; j < k; j++) {
              if (this.commonJS.isNotEmpty(this.inputForm.wareHouse[j].tradePrice)) {
                if (this.commonJS.isNotEmpty(this.inputForm.wareHouse[j].tradeNumber)) {
                  this.inputForm.wareHouse[j].priceSum = this.inputForm.wareHouse[j].tradePrice * this.inputForm.wareHouse[j].tradeNumber
                }
              }
            }
            this.$refs.uploadComponent.newUpload(method, this.inputForm.files, 'reimbursement')
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            this.loading = false
          })
          if (method !== 'edit' && method !== 'view') {
            this.$refs.uploadComponent.newUpload(method, [], 'reimbursement')
          }
        })
      },
      getUpload (p, index) {
        p.then((list) => {
          // list为返回数据
          this.inputForm.wareHouse[index].fileInfoLost = list
          this.inputForm.wareHouse[index].fileNumber = list.length
          this.tableKeyClient = Math.random()
        })
      },
      close () {
        this.method = ''
        this.inputForm.detailInfos = []
        this.inputForm.wareHouse = []
        this.inputForm.amountInfos = []
        this.$refs.uploadComponent.clearUpload()
        this.$refs.inputForm.resetFields()
        this.visible = false
      },
      // 新增
      async insertEvent (type) {
        if (type === 'detail') {
          await this.$refs.detailTable.insert().then((data) => {
            data.wareHouseManId = this.wareHouseManId
            data.wareHouseMan = this.name
            data.wareHouseManOffice = this.officeName
            // this.inputForm.detailInfos.push(data)
            this.inputForm.wareHouse.push(data)
          })
        }
        if (type === 'amount') {
          await this.$refs.amountTable.insert().then((data) => {
            this.inputForm.amountInfos.push(data)
          })
        }
      },
      startForm (callback) {
        this.loading = true
        if (this.commonJS.isNotEmpty(this.inputForm.id)) {
          this.wareHouseService.findById(this.inputForm.id).then(({data}) => {
            // 审核状态不是“未发起”或“暂存”或“撤回”，就弹出提示
            if (this.commonJS.isNotEmpty(data.status) && data.status !== '0' && data.status !== '1' && data.status !== '3') {
              this.loading = false
              this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
              throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            } else {
              this.startFormTrue(callback)
            }
          })
        } else {
          this.startFormTrue(callback)
        }
      },
      reapplyForm (callback) {
        this.loading = true
        this.wareHouseService.findById(this.inputForm.id).then(({data}) => {
          if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
            this.loading = false
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
          } else {
            this.startFormTrue(callback)
          }
        })
      },
      // 暂存
      async saveForm (callback) {
        this.loading = true
        if (this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          return
        }
        if (this.commonJS.isEmpty(this.inputForm.files)) {
          this.inputForm.files = []
        }
        this.inputForm.files = this.$refs.uploadComponent.getDataList()
        this.inputForm.status = '1'
        this.wareHouseService.save(this.inputForm).then(({data}) => {
          callback()
          this.$refs.inputForm.resetFields()
          this.loading = false
        }).catch(() => {
          this.$refs.inputForm.resetFields()
          this.loading = false
        })
      },
      // 送审
      async startFormTrue (callback) {
        this.loading = true
        this.$refs['inputForm'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            if (this.commonJS.isEmpty(this.inputForm.files)) {
              this.inputForm.files = []
            }
            if (this.commonJS.isEmpty(this.inputForm.wareHouse)) {
              this.$message.error('至少填写一条入库详情信息')
              this.loading = false
              return
            } else {
              let i = this.inputForm.wareHouse.length
              for (let j = 0; j < i; j++) {
                let k = j + 1
                if (this.commonJS.isEmpty(this.inputForm.wareHouse[j].wareHouseMan)) {
                  this.$message.error('入库详情第' + k + '行请选择入库人')
                  this.loading = false
                  return
                }
                if (this.commonJS.isEmpty(this.inputForm.wareHouse[j].wareHouseType)) {
                  this.$message.error('入库详情第' + k + '行请选择入库类型')
                  this.loading = false
                  return
                }
              }
            }
            this.inputForm.files = this.$refs.uploadComponent.getDataList()
            this.inputForm.status = '2'
            this.wareHouseService.save(this.inputForm).then(({data}) => {
              this.inputForm.id = data.businessId
              callback(data.businessTable, data.businessId, this.inputForm)
              this.$refs.inputForm.resetFields()
              this.loading = false
            }).catch(() => {
              this.$refs.inputForm.resetFields()
              this.loading = false
            })
          } else {
            this.loading = false
          }
        })
      },
      // 通过
      async agreeForm (callback) {
        this.loading = true
        this.$refs['inputForm'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            if (this.commonJS.isEmpty(this.inputForm.files)) {
              this.inputForm.files = []
            }
            this.inputForm.files = this.$refs.uploadComponent.getDataList()
            console.log('this.inputForm.procInsId', this.inputForm.procInsId)
            this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then(({data}) => {
              if (this.commonJS.isNotEmpty(data)) {
                console.log('进来了', data)
                if (data === '公司领导审批') {
                  this.inputForm.status = '5'
                }
              }
              this.wareHouseService.save(this.inputForm).then(({data}) => {
                callback(data.businessTable, data.businessId, this.inputForm)
                this.loading = false
              }).catch(() => {
                this.loading = false
              })
            })
          } else {
            this.loading = false
          }
        })
      },
      async updateStatusById (type, callback) {
        this.loading = true
        if (await this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        } else {
          if (type === 'reject' || type === 'reback') {
            this.wareHouseService.findById(this.inputForm.id).then(({data}) => {
              if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
                this.loading = false
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                if (type === 'reject') {
                  // 驳回
                  this.inputForm.status = '4'
                }
                if (type === 'reback') {
                  // 撤回
                  this.inputForm.status = '3'
                }
                if (type === 'reject' || type === 'reback') {
                  let param = {status: this.inputForm.status, id: this.inputForm.id}
                  this.wareHouseService.updateStatusById(param).then(() => {
                    this.loading = false
                    callback()
                  })
                }
              }
            })
          } else if (type === 'hold') {
            this.wareHouseService.findById(this.inputForm.id).then(({data}) => {
              if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
                this.loading = false
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                // 终止
                let param = {status: '1', id: this.inputForm.id}
                this.wareHouseService.updateStatusById(param).then(() => {
                  this.loading = false
                  callback()
                })
              }
            })
          }
        }
      },
      twoDecimalPlaces (num, index) {
        let str = num.toString()
        var len1 = str.substr(0, 1)
        var len2 = str.substr(1, 1)
        // eslint-disable-next-line eqeqeq
        if (str.length > 1 && len1 == 0 && len2 != '.') {
          str = str.substr(1, 1)
        }
        // eslint-disable-next-line eqeqeq
        if (len1 == '.') {
          str = ''
        }
        // eslint-disable-next-line eqeqeq
        if (str.indexOf('.') != -1) {
          var str_ = str.substr(str.indexOf('.') + 1)
          // eslint-disable-next-line eqeqeq
          if (str_.indexOf('.') != -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
          if (str_.length > 2) {
            this.$message.warning(`金额小数点后只能输入两位，请正确输入！`)
            return (str = '')
          }
        }
        // eslint-disable-next-line no-useless-escape
        this.inputForm.detailInfos[index].priceSum = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
      },
      countAmount (row) {
        let amount
        let taxAmount
        let count = 0
        if (!this.commonJS.isEmpty(row.amount)) {
          amount = parseFloat(row.amount)
          count = count + amount
        }
        if (!this.commonJS.isEmpty(row.taxAmount)) {
          taxAmount = parseFloat(row.taxAmount)
          count = count + taxAmount
        }
        row.count = parseFloat(count).toFixed(2)
      },
      getProgram (rows) {
        this.inputForm.detailInfos[this.indexRow].projectId = rows[0].id
        this.inputForm.detailInfos[this.indexRow].projectName = rows[0].name
        this.inputForm.detailInfos[this.indexRow].reportNumber = rows[0].reportNo
        this.indexRow = ''
        this.$forceUpdate()
      },
      getProgramForType (rows) {
        this.inputForm.wareHouse[this.indexRow].wareHouseTypeId = rows.id
        this.inputForm.wareHouse[this.indexRow].wareHouseType = rows.name
        // this.inputForm.detailInfos[this.indexRow].procurementType = rows.name
        this.indexRow = ''
        this.$forceUpdate()
      },
      getProgramForUser (rows) {
        this.inputForm.wareHouse[this.indexRow].wareHouseManId = rows[0].id
        this.inputForm.wareHouse[this.indexRow].wareHouseMan = rows[0].name
        this.inputForm.wareHouse[this.indexRow].deptId = rows[0].parentId
        this.inputForm.wareHouse[this.indexRow].wareHouseManOffice = rows[0].officeName
        this.indexRow = ''
        this.$forceUpdate()
      },
      getUserInfo (rows) {
        console.log('rows', rows)
      },
      openContractForm () {
        this.$refs.purchaseChooseForm.init()
      },
      getContract (row) {
        this.materialManagementService.findById(row.id).then(({data}) => {
          this.inputForm.detailInfos = data.detailInfos
          this.inputForm.purchaseNo = data.purchaseNo
          let i = this.inputForm.detailInfos.length
          for (let j = 0; j < i; j++) {
            if (this.commonJS.isNotEmpty(this.inputForm.detailInfos[j].tradePrice)) {
              if (this.commonJS.isNotEmpty(this.inputForm.detailInfos[j].tradeNumber)) {
                this.inputForm.detailInfos[j].priceSum = this.inputForm.detailInfos[j].tradePrice * this.inputForm.detailInfos[j].tradeNumber
              }
            }
          }
        })
        this.$forceUpdate()
      },
      // 查看采购详情
      async viewContract (purchaseNo) {
        this.wareHouseService.findRequestId(purchaseNo).then(({data}) => {
          this.$refs.updateInfoForm.init('view', data)
        }).catch(() => {
        })
      },
      footerMethod ({ columns, data }) {
        const footerData = [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return '商品总价'
            }
            if (['priceSum'].includes(column.property)) {
              // eslint-disable-next-line no-undef
              this.inputForm.tradeTotalPrice = XEUtils.sum(data, column.property)
              return XEUtils.sum(data, column.property)
            }
            return null
          })
        ]
        return footerData
      },
      footerMethod2 ({ columns, data }) {
        const footerData = [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return '商品总价'
            }
            if (['priceSum'].includes(column.property)) {
              // eslint-disable-next-line no-undef
              this.inputForm.wareHouseTotalPrice = XEUtils.sum(data, column.property)
              return XEUtils.sum(data, column.property)
            }
            if (['actualPrice'].includes(column.property)) {
              // eslint-disable-next-line no-undef
              this.inputForm.wareHouseActualPrice = XEUtils.sum(data, column.property)
              return XEUtils.sum(data, column.property)
            }
            return null
          })
        ]
        return footerData
      },
      // 值改变事件
      changeValue () {
        let i = this.inputForm.detailInfos.length
        for (let j = 0; j < i; j++) {
          if (this.commonJS.isNotEmpty(this.inputForm.detailInfos[j].tradePrice)) {
            if (this.commonJS.isNotEmpty(this.inputForm.detailInfos[j].tradeNumber)) {
              // parseFloat(item.account).toFixed(2)
              this.inputForm.detailInfos[j].priceSum = parseFloat(parseFloat(this.inputForm.detailInfos[j].tradePrice) * parseFloat(this.inputForm.detailInfos[j].tradeNumber)).toFixed(2)
            }
          }
        }
      },
      // 值改变事件
      changeValue2 () {
        let i = this.inputForm.wareHouse.length
        for (let j = 0; j < i; j++) {
          if (this.commonJS.isNotEmpty(this.inputForm.wareHouse[j].tradePrice)) {
            if (this.commonJS.isNotEmpty(this.inputForm.wareHouse[j].tradeNumber)) {
              // parseFloat(item.account).toFixed(2)
              this.inputForm.wareHouse[j].priceSum = parseFloat(parseFloat(this.inputForm.wareHouse[j].tradePrice) * parseFloat(this.inputForm.wareHouse[j].tradeNumber)).toFixed(2)
            }
          }
        }
      },
      seeFileInfo (index) {
        if (this.commonJS.isEmpty(this.inputForm.detailInfos[index].fileInfoLost)) {
          this.inputForm.detailInfos[index].fileInfoLost = []
        }
        this.$refs.materialManagementDialog.newUpload('view', this.inputForm.detailInfos[index].fileInfoLost, null, null, null, null, null, false, index)
      },
      seeFileInfo2 (index) {
        if (this.commonJS.isEmpty(this.inputForm.wareHouse[index].fileInfoLost)) {
          this.inputForm.wareHouse[index].fileInfoLost = []
        }
        this.$refs.materialManagementDialog.newUpload('view', this.inputForm.wareHouse[index].fileInfoLost, null, null, null, null, null, false, index)
      },
      sss2 (index) {
        if (this.commonJS.isEmpty(this.inputForm.wareHouse[index].fileInfoLost)) {
          this.inputForm.wareHouse[index].fileInfoLost = []
        }
        this.$refs.materialManagementDialog.newUpload(null, this.inputForm.wareHouse[index].fileInfoLost, null, null, null, null, null, false, index)
      },
      // 采购人下拉弹窗
      userPullListForm (rowIndex) {
        this.indexRow = rowIndex
        this.$refs.userPullForm.init()
      },
      // 采购类型下拉弹窗
      typePullForm (rowIndex) {
        this.indexRow = rowIndex
        this.$refs.materialTypePullForm.init()
      },
      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'detail') {
          this.$refs.detailTable.remove(row)
          // this.inputForm.detailInfos.splice(rowIndex, 1)
          this.inputForm.wareHouse.splice(rowIndex, 1)
        }
        if (type === 'amount') {
          this.$refs.amountTable.remove(row)
          this.inputForm.amountInfos.splice(rowIndex, 1)
        }
      },
      ifSameValue () {
        let i = this.inputForm.wareHouse.length
        for (let j = 0; j < i; j++) {
          if (j + 1 < i) {
            if (this.inputForm.wareHouse[j].wareHouseTypeId === this.inputForm.wareHouse[j + 1].wareHouseTypeId) {
              if (this.commonJS.isNotEmpty(this.inputForm.wareHouse[j].tradeName) &&
                this.commonJS.isNotEmpty(this.inputForm.wareHouse[j + 1].tradeName) && this.inputForm.wareHouse[j].tradeName === this.inputForm.wareHouse[j + 1].tradeName) {
                // parseFloat(item.account).toFixed(2)
                this.inputForm.wareHouse.splice(j + 1, 1)
                this.$message.warning(`同种入库类型的商品名称只能输入一条信息！`)
              }
            }
          }
        }
      },
      openContractChooseForm () {
        this.$refs.contractChooseForm.init()
      },
      getContract3 (row) {
        console.log('row', row)
        this.inputForm.contractNo = row.contractNo
        // this.materialManagementService.findById(id).then(({data}) => {
        //   this.inputForm.detailInfos = data.detailInfos
        //   this.inputForm.purchaseNo = data.purchaseNo
        //   let i = this.inputForm.detailInfos.length
        //   for (let j = 0; j < i; j++) {
        //     if (this.commonJS.isNotEmpty(this.inputForm.detailInfos[j].tradePrice)) {
        //       if (this.commonJS.isNotEmpty(this.inputForm.detailInfos[j].tradeNumber)) {
        //         this.inputForm.detailInfos[j].priceSum = this.inputForm.detailInfos[j].tradePrice * this.inputForm.detailInfos[j].tradeNumber
        //       }
        //     }
        //   }
        // })
        this.$forceUpdate()
      }
    }
  }
</script>
