<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      v-dialogDrag
      append-to-body
      width="1300px"
      @close="close"
      @keyup.enter.native=""
      :visible.sync="visible">
    <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="true"
             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="large"
              @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%"
              placement="bottom-start"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采购编号" prop="purchaseNo"
                        :rules="[]">
            <el-input :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="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>

      <div v-if="commonJS.isNotEmpty(inputForm.purchaseNo)">
        <el-divider content-position="left" ><i class="el-icon-document" style="font-weight: bold;font-size: 16px;color:#409EFF"></i>
          <el-link @click="viewContract(inputForm.purchaseNo)"><span style="font-weight: bold;font-size: 16px;color:#409EFF">&nbsp;采购详情</span></el-link>
        </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: 3em"
          >
            <vxe-column min-width="100" align="center" field="purchaserAgent" title="采购人" ></vxe-column>
            <vxe-column min-width="100" align="center" field="procurementOffice" title="采购部门" ></vxe-column>
            <vxe-column min-width="100" align="center" field="procurementType" title="采购类型" ></vxe-column>
            <vxe-column min-width="220" align="center" field="tradeName"  title="商品名称" ></vxe-column>
            <vxe-column min-width="130px" align="center" field="supplierName" title="供应商" ></vxe-column>
            <vxe-column min-width="100" align="center" field="tradePrice" title="商品单价(元)" ></vxe-column>
            <vxe-column min-width="80" align="center" field="tradeNumber" title="商品数量" ></vxe-column>
            <vxe-column min-width="100" align="center" field="priceSum" title="商品总价" ></vxe-column>
            <vxe-column min-width="100" align="center" field="company" title="单位" ></vxe-column>
            <vxe-column min-width="100" align="center" field="remarks" title="备注" ></vxe-column>
            <vxe-column align="center" title="操作" fixed="right" width="80">
              <template v-slot="scope">
                <el-button size="mini" type="primary" :disabled="false" @click="seeFileInfo(scope.$rowIndex)"plain>附件</el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </el-row>
      </div>

      <el-divider content-position="left"><i class="el-icon-document"></i>
        入库详情
      </el-divider>
      <el-row :gutter="15" >
        <vxe-table
          border
          show-footer
          show-overflow
          :footer-method="footerMethod2"
          ref="detailTableWare"
          class="vxe-table-element"
          :data="inputForm.wareHouse"
          style="margin-left: 3em"
          :row-class-name="rowClassName"
          :key="tableKey"
        >
          <vxe-column min-width="110px" align="center" field="wareHouseMan" title="入库人">
            <template v-slot="scope">
              <span v-if="scope.row.upFlag === '1'"> {{scope.row.wareHouseMan}}(修改前) </span>
              <span v-else-if="scope.row.upFlag === '2'"> {{scope.row.wareHouseMan}}(已删除) </span>
              <span v-else-if="scope.row.upFlag === '0' && commonJS.isNotEmpty(scope.row.sourceId)"> {{scope.row.wareHouseMan}}(修改后) </span>
              <span v-else-if="scope.row.upFlag === '0' && commonJS.isEmpty(scope.row.sourceId)"> {{scope.row.wareHouseMan}} </span>
            </template>
          </vxe-column>
          <vxe-column min-width="100px" align="center" field="wareHouseManOffice" title="入库部门"></vxe-column>
          <vxe-column min-width="100px" align="center" field="wareHouseType" title="入库类型"></vxe-column>
          <vxe-column min-width="180px" align="center" field="tradeName" title="商品名称" ></vxe-column>
          <vxe-column min-width="130px" align="center" field="supplierName" title="供应商" ></vxe-column>
          <vxe-column min-width="80px" align="center" field="tradeNumber" title="商品数量" ></vxe-column>
          <vxe-column min-width="80px" align="center" field="company" title="单位"></vxe-column>
          <vxe-column min-width="80px" align="center" field="tradePrice" title="商品单价(元)" ></vxe-column>
          <vxe-column min-width="80px" align="center" field="priceSum" title="商品总价"></vxe-column>
          <vxe-column min-width="80px" align="center" field="actualPrice" title="实际价格"></vxe-column>
          <vxe-column min-width="100px" align="center" field="remarks" title="备注"></vxe-column>
          <vxe-column align="center" fixed="right" title="操作" width="80px">
            <template v-slot="scope">
              <el-button size="mini" type="primary" v-if="scope.row.upFlag !== '1'" :disabled="false" @click="seeFileInfo2(scope.$rowIndex)" plain>附件</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </el-row>
      <el-row>
        <el-col :span="24" style="margin-top: 20px">
          <el-form-item label="修改原因" prop="updateCause" :rules="[{required: true, message: '修改原因不能为空', trigger: 'blur'}]">
            <el-input type="textarea"
                      :rows="5"
                      maxlength="500"
                      placeholder="请填写修改原因"
                      show-word-limit
                      v-model="inputForm.updateCause"></el-input>
          </el-form-item>
        </el-col>
      </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>
    <UserPullForm ref="userPullForm" @getProgramForUser="getProgramForUser"></UserPullForm>
      <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="close()" icon="el-icon-circle-close">关闭</el-button>
    </span>
    </el-dialog>
  </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 {
        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: [], // 附件信息
          functionFlag: ''
        },
        keyWatch: '',
        tableKey: ''
      }
    },
    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: {},
    components: {
      MaterialManagementDialog,
      PurchaseChooseForm,
      UserSelect,
      UpLoadComponent,
      SelectUserTree,
      SelectTree,
      CwProgramPageForm,
      MaterialTypePullForm,
      UserPullForm,
      ContractChooseForm,
      UpdateInfoForm
    },
    computed: {},
    watch: {
      'loading': {
        handler (newVal) {
          this.$refs.uploadComponent.changeLoading(newVal)
        }
      }
    },
    methods: {
      init (id) {
        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: [], // 附件信息
          functionFlag: ''
        }
        this.title = '入库修改历史详情'
        this.inputForm.id = id
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.loading = true
          this.$refs.inputForm.resetFields()
          this.wareHouseService.findHiByHiId(this.inputForm.id, this.status).then(({data}) => {
            this.$refs.uploadComponent.clearUpload()
            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)
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            if (this.commonJS.isNotEmpty(this.inputForm.detailInfos)) {
              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
                  }
                }
              }
            }
            if (this.commonJS.isNotEmpty(this.inputForm.wareHouse)) {
              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('view', this.inputForm.files, 'wareHouse')
            this.loading = false
            this.tableKey = Math.random()
          })
        })
      },
      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.inputForm = {
          procInsId: '',
          wareHouseTotalPrice: '',
          wareHouseActualPrice: '',
          tradeTotalPrice: '',
          fileInfoLost: [],
          purchaseNo: '',
          handledBy: '',
          handledById: '',
          handledByOffice: '',
          wareHouseName: '',
          wareHouseNumber: '',
          userId: '',
          wareHouseDate: '',
          remarks: '',
          detailInfos: [],
          wareHouse: [],
          files: [],
          functionFlag: ''
        }
        this.method = ''
        this.inputForm.functionFlag = ''
        this.inputForm.detailInfos = []
        this.inputForm.wareHouse = []
        this.inputForm.amountInfos = []
        this.$refs.uploadComponent.clearUpload()
        this.$refs.inputForm.resetFields()
        this.visible = false
      },
      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()
      },
      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
      },
      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)
      },
      // 采购类型下拉弹窗
      typePullForm (rowIndex) {
        this.indexRow = rowIndex
        this.$refs.materialTypePullForm.init()
      },
      // 列表行颜色
      rowClassName ({ row, rowIndex }) {
        if (row.upFlag === '1') { // 修改前
          return 'row-grey'
        } else if (row.upFlag === '2') { // 已删除
          return 'row-red'
        } else if (row.upFlag === '0' && this.commonJS.isNotEmpty(row.sourceId)) { // 修改后
          return 'row-green'
        } else if (row.upFlag === '0' && this.commonJS.isEmpty(row.sourceId)) { // 未被修改过的数据
          return ''
        }
      }
    }
  }
</script>
<style scoped>
  .el-divider__text {
    font-size: 16px;
    font-weight: bold;
  }
  /deep/  .row-green {
    /*background-color: #67c23ad1;*/
    /*color: #fff;*/
    font-weight: bold;
  }
  /deep/  .row-grey {
    background-color: #b8b7b7;
    color: #fff;
  }
  /deep/  .row-red {
    background-color: #f56c6c66;
    /*color: #fff;*/
    font-weight: bold;
  }
</style>
