<template>
    <div>
        <div class="my-title">{{ !id?'新增':'修改' }}</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="contractCode">
                <el-input v-model="dataForm.contractCode" disabled placeholder="合同编码由系统生成"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同评审编码" prop="reCode">
                <el-select
                  v-model="dataForm.reCode"
                  remote
                  placeholder="请选择">
                  <el-option
                    v-for="item in optionsReCode"
                    :key="item.reCode"
                    :label="item.customerName + ' (' + item.reCode + ' )'"
                    :value="item.reCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同号" prop="contractNumber">
                <el-input v-model="dataForm.contractNumber" placeholder="合同号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="my-row">
            <el-col :span="8">
              <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="dataForm.projectName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同交期" prop="deliveryTime">
                <el-date-picker
                  v-model="dataForm.deliveryTime"
                  value-format="yyyy-MM-dd"
                  type="date">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际交付日期" prop="actualDeliveryTime">
                <el-input v-model="dataForm.actualDeliveryTime" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="my-row" style="margin-top: 20px">
            <el-form-item label="备注" prop="notes">
              <el-input type="textarea" v-model="dataForm.notes"></el-input>
            </el-form-item>
          </el-row>
          <el-row v-if="isProductListVisible">
            <div class="title"><span style="color: red">*</span> 物料列表</div>
            <el-table
              :data="productList"
              border
              style="width: 100%;">
              <el-table-column
                label="序号"
                type="index"
                width="50"
                align="center">
              </el-table-column>
              <el-table-column
                prop="mapNumber"
                header-align="center"
                align="center"
                min-width="120"
                :show-tooltip-when-overflow="true"
                label="图号">
              </el-table-column>
              <el-table-column
                prop="productName"
                header-align="center"
                align="center"
                min-width="120"
                :show-tooltip-when-overflow="true"
                label="物料名称">
              </el-table-column>
              <el-table-column
                prop="productSpecifications"
                header-align="center"
                align="center"
                min-width="120"
                :show-tooltip-when-overflow="true"
                label="规格">
              </el-table-column>
              <el-table-column
                prop="cnt"
                header-align="center"
                align="center"
                min-width="160"
                label="数量">
              </el-table-column>
               <el-table-column
                prop="unitName"
                header-align="center"
                align="center"
                min-width="160"
                label="单位">
              </el-table-column>
              <el-table-column
                prop="price"
                header-align="center"
                align="center"
                min-width="100"
                label="含税单价">
                 <template slot-scope="scope">
                  <span>{{ scope.row.price == null ? '0' : scope.row.price }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="amount"
                header-align="center"
                align="center"
                min-width="100"
                label="含税总价">
                <template slot-scope="scope">
                  <span>{{ (scope.row.cnt*scope.row.price).toFixed(1) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="rate"
                header-align="center"
                align="center"
                min-width="120"
                label="税率">
                <template slot-scope="scope">
                  <span>{{scope.row.rate}}</span>&nbsp;%
                </template>
              </el-table-column>
              <el-table-column
                prop="notes"
                header-align="center"
                align="center"
                min-width="140"
                :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="updateProductHandle(scope.row)">编辑</el-button>
                  <el-button style="color: red" type="text" size="small" @click="deleteProductHandle(scope.row.recordId)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row style="text-align: center; margin-top: 10px;">
              <el-button type="primary" icon="el-icon-plus" @click="addProductHandle()"></el-button>
            </el-row>
          </el-row>
          <el-row class="my-row">
            <upload-component :display-star="false" :title="'附件'" :accept="'*'" :file-obj-list="fileList" @uploadSuccess="uploadSuccess"/>
          </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-or-update v-if="productUpdateVisible"  ref="productDialog" @addItem="addItem" />
<!--      <add-or-update-product v-if="productUpdateVisible" ref="productDialog" @changeItem="changeItem"/>-->
<!--      <template-chose v-if="inboundVisible" ref="inbound" @addItems="addItems" />-->
    </div>
</template>

<script>
  import UploadComponent from '../common/upload-component'
  import TemplateChose from '../product/template-chose'
  import AddOrUpdate from '../product/template-add-or-update'
  import { getReviewCodeList, geContractBookDetail, getCommunicationList } from '@/api/cus'

export default {
    name: 'contract-record-add-or-update',
    components: {
      UploadComponent,
      TemplateChose,
      AddOrUpdate
    },
    computed: {
      orgId: {
        get () { return this.$store.state.user.orgId }
      }
    },
    watch: {
      'dataForm.reCode' (value) {
        let d = this.optionsReCode.find(item => item.reCode === value)
        if (!d) return
        getCommunicationList(d.coId).then(({data}) => {
          if (data && data.code === '200') {
            this.isProductListVisible = true
            this.productList = data.data
          }
        })
      }
    },
    data () {
      return {
        visible: false,
        optionsReCode: [],
        fileList: [],
        dataList: [],
        isProductListVisible: false, // 物料列表是否显示
        productUpdateVisible: false, // 物料修改对话框是否显示
        inboundVisible: false, // 物料新增对话框是否显示
        productList: [],
        id: 0,
        dataForm: {},
        dataRule: {
          reCode: [{ required: true, message: '请选择合同评审编码', trigger: 'change' }],
          contractNumber: [{ required: true, message: '合同号不能为空', trigger: 'blur' }],
          deliveryTime: [{ required: true, message: '合同交期不能为空', trigger: 'change' }],
          projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }]
        }
      }
    },
    methods: {
      onChose () {
        this.$emit('onChose')
      },
      async init (id) {
        this.fileList = []
        this.dataForm = {}
        // this.optionsReCode = []
        this.visible = true
        this.id = id || 0
        // 获取合同评审编码列表
        await getReviewCodeList().then(({data}) => {
          if (data) {
            this.optionsReCode = data.data
          }
        })
        // 详情
        if (!id) return
        this.isProductListVisible = true
        await geContractBookDetail(this.id).then(({data}) => {
          if (data && data.code === '200') {
            this.dataForm = data.data
            // 附件
            if (data.data.attachList) {
              data.data.attachList.forEach((item) => {
                this.fileList.push({
                  name: item.fileName,
                  url: item.url,
                  id: item.url
                })
              })
            }
            if (data.data.cusCBookProducts) {
              data.data.cusCBookProducts.forEach((item) => {
                this.addItem(item)
              })
            }
          }
        })
      },
      uploadSuccess (fileList) {
        this.fileList = fileList
      },
      validateField (type) {
        this.$refs.dataForm.validateField(type)
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 附件
            let fList = this.fileList
            if (fList.length > 0) {
              this.dataForm.attachList = []
              for (let i = 0; i < fList.length; i++) {
                this.dataForm.attachList.push({
                  fileName: fList[i].name,
                  url: fList[i].url
                })
              }
            }
            if (this.productList.length === 0) {
              this.$message.error('请选择任务单物料明细')
              return
            }
            this.dataForm.cusCBookProducts = this.productList
            // 物料明细
            this.$http({
              url: this.$http.adornUrl(`/biz-service/cusContractBook/${!this.id ? 'save' : 'update'}`),
              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.onChose()
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 删除物料项
      deleteProductHandle (recordId) {
        this.productList.splice(this.productList.findIndex((item) => item.recordId === recordId), 1)
      },
      // 编辑物料
      updateProductHandle (row) {
        this.productUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.productDialog.init(1, row)
        })
      },
      // 添加物料
      addProductHandle () {
        this.productUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.productDialog.init(1)
        })
      },
      addItem (item) {
        if (!item) return
        if (!item.recordId) {
          item.recordId = Math.round(Math.random() * 1000000)
        }
        if (this.productList.findIndex(item1 => item1.recordId === item.recordId) === -1) {
          this.productList.push({
            ...item
          })
        }
      }
    }
  }
</script>

<style scoped>

</style>
