<template>
  <div>
    <el-dialog
      :title="!id ? '新增': display ? '详情' : '修改'"
      width="70%"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <!-- 工作流 -->
      <div v-show="display && dataForm.workFlowBusinessExt">
        <el-steps :active="dataForm.workFlowBusinessExt?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="purchaseCode">
              <el-input v-model="dataForm.purchaseCode" :disabled="display || !id" 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" :disabled="display">
                <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>
        <el-row class="my-row">
          <el-col :span="8">
            <el-form-item label="采购类别" prop="purchaseType">
              <el-select
                v-model="dataForm.purchaseType"
                :disabled="display"
                remote
                placeholder="请选择">
                <el-option
                  v-for="item in optionsType"
                  :key="item.code"
                  :label="item.value"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="my-row">
          <el-form-item label="备注" prop="notes">
            <el-input type="textarea" v-model="dataForm.notes" :disabled="display"></el-input>
          </el-form-item>
        </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="name"
              header-align="center"
              align="center"
              min-width="120"
              label="物品名称">
            </el-table-column>
            <el-table-column
              prop="specification"
              header-align="center"
              align="center"
              min-width="120"
              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="price"
              header-align="center"
              align="center"
              label="不含税单价">
            </el-table-column>
            <el-table-column
              prop="taxPrice"
              header-align="center"
              align="center"
              label="含税单价">
            </el-table-column>
            <el-table-column
              prop="taxAmount"
              header-align="center"
              align="center"
              label="含税总价">
            </el-table-column>
            <el-table-column
              prop="taxRate"
              header-align="center"
              align="center"
              :formatter="formatPercent"
              label="税率">
            </el-table-column>
            <el-table-column
              prop="notes"
              header-align="center"
              align="center"
              label="备注">
            </el-table-column>
            <el-table-column
              v-if="!display"
              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>
          <span>合计（含税）： {{totalAmount}}</span>
        </el-row>
        <el-row v-if="!display" 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="visible = false">取消</el-button>
      <el-button v-if="!display" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    </el-dialog>
    <!-- 新增物品 -->
    <Add v-show="addMaterialVisible" ref="comAddMaterial" @addItem="addMaterialCallback"/>
  </div>
</template>

<script>
  import Add from './add-material'
  import { getDictList } from '@/api/dict'
  import { getPurchaseDetail } from '@/api/sale'
  import { getUserInfo } from '@/api/user'
  import { dealStepData, dealStepLogs } from '@/api/util'
  import UserComponent from '../common/user-component'
  export default {
    name: 'purchase-add-or-update',
    components: {
      UserComponent,
      Add
    },
    data () {
      return {
        visible: false,
        display: false,
        dataList: [],
        id: 0,
        dataForm: {},
        optionsType: [],
        materialDetails: [],
        addMaterialVisible: false,
        totalAmount: 0,
        dataRule: {
          purchaseType: [{ required: true, message: '请选择采购类别', trigger: 'change' }],
          applierId: [{ required: true, message: '请选择申请人', trigger: 'change' }]
        },
        stepList: [],
        logList: []
      }
    },
    methods: {
      // 获取采购类别字典
      getTypeList () {
        getDictList({type: 'purchase_type'}).then(({data}) => {
          if (data) {
            this.optionsType = data
          }
        })
      },
      async init (id, display) {
        this.materialDetails = []
        this.dataForm = {
          payType: '0'
        }
        this.visible = true
        this.id = id || 0
        this.display = display
        // 获取采购类别字典
        if (!id || !display) {
          this.getTypeList()
        }
        if (!id) return
        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.details) {
              this.materialDetails = []
              this.materialDetails = data.data.details
              this.calTotal()
            }
          }
        })
      },
      validateField (type) {
        this.$refs.dataForm.validateField(type)
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 添加采购物品明细
            this.dataForm.details = this.materialDetails
            this.$http({
              url: !this.id ? this.$http.adornUrl(`/biz-service/purchase/save`) : this.$http.adornUrl(`/biz-service/purchase/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.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      addMaterial () {
        this.addMaterialVisible = true
        this.$nextTick(() => {
          this.$refs.comAddMaterial.init()
        })
      },
      addMaterialHandle (row, disable) {
        this.addMaterialVisible = true
        this.$nextTick(() => {
          this.$refs.comAddMaterial.init(row.detailId, disable, row)
        })
      },
      deleteMaterialHandle (id) {
        this.materialDetails.splice(this.materialDetails.findIndex((item) => item.id === id))
        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)
        }
        this.materialDetails.push(data)
        this.calTotal()
      },
      calTotal () {
        let total = 0
        if (this.materialDetails) {
          this.materialDetails.forEach((item) => {
            total += item.taxAmount ? Number(item.taxAmount) : 0
          })
        }
        this.totalAmount = total
      },
      // 百分比
      formatPercent (row) {
        if (!row.taxRate) return ''
        let str = (Number(row.taxRate * 100)).toFixed(0)
        str += '%'
        return str
      }
    }
  }
</script>

<style scoped>

</style>
