<template>
  <div>
    <el-dialog
      :title="!id ? '新增': display ? '详情' : '修改'"
      width="70%"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <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-col :span="8" style="padding-left: 20px">
            <el-form-item label="申请人" prop="applierId">
              <el-input v-if="display" v-model="dataForm.applierName" disabled></el-input>
              <el-select v-else
                v-model="dataForm.applierId"
                remote
                         filterable
                         :remote-method="remoteApplier"
                         @change="onApplierChanged"
                placeholder="请选择">
                <el-option
                  v-for="item in optionsApplier"
                  :key="item.code"
                  :label="item.value"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 20px">
            <el-form-item label="申请部门" prop="deptName">
              <el-input v-model="dataForm.deptName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="my-row">
          <el-form-item label="备注" prop="notes">
            <el-input v-model="dataForm.notes" :disabled="display" placeholder="备注"></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 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 { getUserList } from '@/api/user'
  export default {
    name: 'purchase-add-or-update',
    components: {
      Add
    },
    data () {
      return {
        visible: false,
        display: false,
        dataList: [],
        id: 0,
        dataForm: {},
        optionsType: [],
        optionsApplier: [],
        materialDetails: [],
        addMaterialVisible: false,
        dataRule: {
          purchaseType: [{ required: true, message: '请选择采购类别', trigger: 'change' }],
          applierId: [{ required: true, message: '请选择申请人', trigger: 'change' }]
        }
      }
    },
    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.details) {
              this.materialDetails = []
              this.materialDetails = data.data.details
            }
          }
        })
      },
      validateField (type) {
        this.$refs.dataForm.validateField(type)
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/biz-service/purchase/save`),
              method: 'post',
              data: this.$http.adornData({...this.dataForm, orgId: this.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)
              }
            })
          }
        })
      },
      // 获取申请人
      async remoteApplier (query) {
        if (!query) return
        const params = {
          name: query.trimStart()
        }
        await getUserList(params).then(({data}) => {
          if (data && data.code === '200') {
            this.optionsApplier = []
            data.data.records.forEach((item) => {
              this.optionsApplier.push({
                code: item.userId,
                value: item.name + '  (用户名: ' + item.username + ')',
                orgId: item.orgId,
                orgName: item.orgName
              })
            })
          }
        })
      },
      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))
      },
      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)
      },
      // 百分比
      formatPercent (row) {
        if (!row.taxRate) return ''
        console.log('taxRate: ' + row.taxRate)
        let str = (Number(row.taxRate * 100)).toFixed(0)
        str += '%'
        return str
      },
      onApplierChanged (val) {
        if (!val) return
        let item1 = this.optionsApplier.find((item) => item.code === val)
        if (!item1) return
        this.dataForm.deptName = item1.orgName
        this.dataForm.orgId = item1.orgId
      }
    }
  }
</script>

<style scoped>

</style>
