<!-- 采购新增/修改 -->
<template>
  <div>
      <div class="my-title">{{ !id ? '新增': '修改' }}</div>
      <!-- 工作流 -->
      <div v-show="dataForm.workFlowBusinessExt">
        <el-steps :active="dataForm.workFlowBusinessExt&&dataForm.workFlowBusinessExt.workFlowProcessStepList?dataForm.workFlowBusinessExt.workFlowProcessStepList.length + 2:0" align-center style="margin-bottom: 20px">
          <template v-for="(item, i) in stepList">
            <el-step :icon="item.icon" :title="item.title" :description="item.description"></el-step>
          </template>
        </el-steps>
        <el-collapse style="margin-bottom: 20px">
          <el-collapse-item>
            <template slot="title">
              <span style="color: red">审批日志（展开查看更多）：</span>
            </template>
            <template v-for="(item, i) in logList">
              <div>{{++i}}：{{item.approverName}}  {{item.createTime}}  {{item.approvalValue}}</div>
            </template>
          </el-collapse-item>
        </el-collapse>
      </div>
      <!-- 表单 -->
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="auto">
        <el-row class="my-row">
          <el-col :span="8">
            <el-form-item label="采购编码" prop="procurementCode">
              <el-input v-model="dataForm.procurementCode" :disabled="true" placeholder="系统自动生成，无需填写"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16" style="padding-left: 20px">
            <el-form-item label="付款方式" prop="payType">
              <el-radio-group v-model="dataForm.payType">
                <el-radio :label='"0"'>对公转账</el-radio>
                <el-radio :label='"1"'>先行垫付</el-radio>
                <el-radio :label='"2"'>财务预支</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title"><span style="color: red">*</span> 采购物品明细</div>
        <el-row>
          <el-table
            :data="materialDetails"
            border
            style="width: 100%;">
            <el-table-column
              label="序号"
              type="index"
              width="50"
              align="center">
            </el-table-column>
            <el-table-column
              prop="detailId"
              label="ID"
              v-if="false">
            </el-table-column>
            <el-table-column
              prop="materialName"
              header-align="center"
              align="center"
              min-width="120"
              :show-tooltip-when-overflow="true"
              label="物品名称">
            </el-table-column>
            <el-table-column
              prop="specification"
              header-align="center"
              align="center"
              min-width="120"
              :show-tooltip-when-overflow="true"
              label="型号及规格">
            </el-table-column>
            <el-table-column
              prop="purchaseType"
              header-align="center"
              align="center"
              :formatter="formatType"
              label="采购类别">
            </el-table-column>
            <el-table-column
              prop="cnt"
              header-align="center"
              align="center"
              label="数量">
            </el-table-column>
            <el-table-column
              prop="unitName"
              header-align="center"
              align="center"
              label="单位">
            </el-table-column>
            <el-table-column
              prop="deadline"
              header-align="center"
              align="center"
              min-width="160"
              :show-tooltip-when-overflow="true"
              label="采购期限">
            </el-table-column>
            <el-table-column
              prop="batchNumber"
              header-align="center"
              align="center"
              min-width="140"
              :show-tooltip-when-overflow="true"
              label="批次号/用途">
            </el-table-column>
            <el-table-column
              prop="notes"
              header-align="center"
              align="center"
              min-width="160"
              :show-tooltip-when-overflow="true"
              label="备注">
            </el-table-column>
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="150"
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="addMaterialHandle(scope.row, false)">编辑</el-button>
                <el-button style="color: red" type="text" size="small" @click="deleteMaterialHandle(scope.row.detailId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row style="text-align: center; margin-top: 10px;">
          <el-button type="primary" icon="el-icon-plus" @click="addMaterial"></el-button>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="onChose">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-reClick>确定</el-button>
    </span>
    <!-- 新增物品 -->
    <Add v-show="addMaterialVisible" ref="comAddMaterial" :options-type="optionsType" @addItem="addMaterialCallback"/>
  </div>
</template>

<script>
  import Add from './add-material'
  import {getOutsourceDetailByScheduleId, getPurchaseDetail} from '@/api/sale'
  import { dealStepData, dealStepLogs } from '@/api/util'
  import UserComponent from '../common/user-component'
  import {getDictList} from '@/api/dict'
  export default {
    name: 'purchase-add-or-update',
    props: {
      optionsType: {
        type: Array,
        default: () => []
      }
    },
    components: {
      UserComponent,
      Add
    },
    data () {
      return {
        visible: false,
        dataList: [],
        thisOptionsType: this.optionsType,
        id: 0,
        dataForm: {},
        materialDetails: [],
        addMaterialVisible: false,
        dataRule: {
          purchaseType: [{ required: true, message: '请选择采购类别', trigger: 'change' }],
          applierId: [{ required: true, message: '请选择申请人', trigger: 'change' }]
        },
        stepList: [],
        logList: [],
        totalAmount: 0,
        prodProductionIds: [] // 排产ID的集合
      }
    },
    methods: {
      onChose () {
        this.$emit('onChose')
      },
      async init (id, scheduleIds, tableId) {
        if (scheduleIds) {
          this.prodProductionIds = scheduleIds
        }
        this.materialDetails = []
        this.dataForm = {
          payType: '0'
        }
        this.visible = true
        this.id = id || 0
        if (tableId) {
          this.dataForm.tableId = tableId
          this.dataForm.type = 1
        } else {
          // 来源：0：自己/1:排产
          this.dataForm.type = 0
        }
        // 获取采购类别字典
        if (!id) {
          this.getTypeList()
        }
        if (!id && !tableId) return
        if (this.prodProductionIds.length > 0) {
          await getOutsourceDetailByScheduleId({'prodProductionIds': this.prodProductionIds}).then(({data}) => {
            if (data && data.code === '200' && data.data) {
              this.materialDetails = data.data
              if (this.materialDetails && this.materialDetails.length > 0) {
                this.materialDetails.forEach((item) => {
                  item.detailId = Math.round(Math.random() * 1000000)
                })
                this.calTotal()
              }
            }
          })
        } else {
          await getPurchaseDetail(this.id).then(({data}) => {
            if (data && data.code === '200') {
              this.dataForm = data.data
              // 流程图展示
              if (data.data.workFlowBusinessExt) {
                dealStepData(data.data.workFlowBusinessExt.workFlowProcessStepList, this.stepList)
                dealStepLogs(data.data.workFlowBusinessExt.processLogList, this.logList)
              }
              // 获取采购物品明细
              if (data.data.purchaseDetails) {
                this.materialDetails = data.data.purchaseDetails
                if (this.materialDetails && this.materialDetails.length > 0) {
                  this.materialDetails.forEach((item) => {
                    item.detailId = Math.round(Math.random() * 1000000)
                  })
                }
              }
            }
          })
        }
      },
      validateField (type) {
        this.$refs.dataForm.validateField(type)
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 添加采购物品明细
            this.dataForm.purchaseDetails = this.materialDetails
            this.dataForm.type = 0  // 来源：0：自己/1:排产
            this.$http({
              url: this.$http.adornUrl(`/biz-service/purchaseDetail/${!this.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({...this.dataForm, applierId: this.$store.state.user.id, orgId: this.$store.state.user.orgId})
            }).then(({data}) => {
              if (data && data.code === '200') {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.onChose()
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      addMaterial () {
        this.addMaterialVisible = true
        this.$nextTick(() => {
          this.$refs.comAddMaterial.init(null, null, null)
        })
      },
      addMaterialHandle (row, disable) {
        this.addMaterialVisible = true
        this.$nextTick(() => {
          this.$refs.comAddMaterial.init(row.detailId, disable, row)
        })
      },
      deleteMaterialHandle (detailId) {
        this.materialDetails.splice(this.materialDetails.findIndex((item) => item.detailId === detailId), 1)
        // this.calTotal()
      },
      addMaterialCallback (data) {
        if (!data) return
        this.addMaterialVisible = false
        let i = this.materialDetails.findIndex((item) => item.detailId === data.detailId)
        if (i > -1) {
          this.materialDetails.splice(i, 1)
        }
        this.materialDetails.push(data)
        // this.calTotal()
      },
      // 百分比
      formatPercent (row) {
        if (!row.taxRate) return ''
        let str = (Number(row.taxRate * 100)).toFixed(0)
        str += '%'
        return str
      },
      // 采购类型
      formatType (row) {
        if (!row.purchaseType || !this.thisOptionsType) return ''
        const item1 = this.thisOptionsType.find((item) => item.code === row.purchaseType.toString())
        return item1 ? item1.value : ''
      },
      // 获取采购类别字典
      getTypeList () {
        getDictList({type: 'purchase_type'}).then(({data}) => {
          if (data) {
            this.thisOptionsType = data
          }
        })
      },
      calTotal () {
        let total = 0
        if (this.materialDetails) {
          this.materialDetails.forEach((item) => {
            total += item.taxAmount ? Number(item.taxAmount) : 0
          })
        }
        this.totalAmount = total
      }
    }
  }
</script>

<style scoped>

</style>
