<!--  订单新增或修改 -->
<template>
  <div>
    <!-- <el-dialog
      :title="!id ? '新增': display ? '详情' : '修改'"
      width="70%"
      :close-on-click-modal="false"
      :visible.sync="visible"> -->
      <div class="my-title">{{ !id ? '新增': display ? '详情' : '修改' }}</div>
      <!-- 工作流 -->
      <div v-show="display && 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="orderCode">
              <el-input v-model="dataForm.orderCode" :disabled="true" placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 20px">
            <el-form-item label="合同号" prop="contractNumber">
              <el-input v-model="dataForm.contractNumber" :disabled="display || addType === 2" placeholder="合同号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 20px">
            <el-form-item label="客户名称" prop="customerId">
              <el-input v-if="display || addType === 2" v-model="dataForm.customerName" disabled></el-input>
              <cus-component v-else v-model="dataForm.customerId" :disabled="display || addType === 2" :cus-id="dataForm.customerId"></cus-component>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="my-row">
          <el-col :span="8">
            <el-form-item label="业务员" prop="salesmanId">
              <el-input v-if="display || addType === 2" v-model="dataForm.salesmanName" disabled></el-input>
              <user-component v-else v-model="dataForm.salesmanId" :user-id="dataForm.salesmanId" @userSelected="salesmanChanged"></user-component>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 20px">
            <el-form-item label="合同交期" prop="deliveryDate">
              <el-input v-if="display || addType === 2" v-model="dataForm.deliveryDate" disabled></el-input>
              <el-date-picker v-else
                v-model="dataForm.deliveryDate"
                value-format="yyyy-MM-dd"
                type="date">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchNumber">
              <el-input v-model="dataForm.batchNumber" placeholder="批次号" :disabled="display || addType === 2"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row class="my-row">-->
<!--          <upload-component :display="display" :title="'合同扫描件'" :accept="'*'" :file-obj-list="fileList" @uploadSuccess="uploadSuccess"/>-->
<!--        </el-row>-->
        <el-row class="my-row">
          <el-form-item label="备注说明" prop="notes">
            <el-input type="textarea" v-model="dataForm.notes" :disabled="display || addType === 2"  placeholder="备注说明" ></el-input>
          </el-form-item>
        </el-row>
        <el-row class="my-row">
          <div class="title"><span style="color: red">*</span> 订单产品明细</div>
          <el-table
            :data="productDetails"
            border
            style="width: 100%;">
            <el-table-column
              label="序号"
              type="index"
              width="50"
              align="center">
            </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="100"
              label="数量">
            </el-table-column>
            <el-table-column
              prop="productNumber"
              header-align="center"
              align="center"
              min-width="160"
              :show-tooltip-when-overflow="true"
              label="订单编号">
            </el-table-column>
            <el-table-column
              prop="price"
              header-align="center"
              align="center"
              min-width="100"
              label="含税单价">
            </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="100"
              label="税率">
              <template slot-scope="scope">
                {{scope.row.rate}}%
              </template>
            </el-table-column>
            <el-table-column
              prop="notes"
              header-align="center"
              align="center"
              width="120"
              :show-tooltip-when-overflow="true"
              label="备注">
            </el-table-column>
            <el-table-column
              prop="relatedProduct"
              header-align="center"
              align="center"
              width="120"
              :show-tooltip-when-overflow="true"
              label="产品关联">
            </el-table-column>
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="100"
              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 v-show="!display" type="primary" icon="el-icon-plus" @click="addProduct"></el-button>
          </el-row>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="onChose">取消</el-button>
          <el-button v-if="!display" type="primary" @click="dataFormSubmit()">确定</el-button>
        </span>
    <!-- </el-dialog> -->
    <add-or-update v-if="productListVisible"  ref="productList" @addItem="addItem" />
  </div>
</template>

<script>
  // import templateChose from '../product/template-chose'
  import { getOrderDetail } from '@/api/sale'
  import UserComponent from '../common/user-component'
  // import {toNumber} from '@/utils/common'
  import UploadComponent from '../common/upload-component'
  import { dealStepData, dealStepLogs } from '@/api/util'
  import CusComponent from '../common/cus-component'
  import AddOrUpdate from '../product/template-add-or-update'

  export default {
    name: 'order-add-or-update',
    components: {CusComponent, UploadComponent, UserComponent, AddOrUpdate},
    computed: {
      orgId: {
        get () { return this.$store.state.user.orgId }
      }
    },
    data () {
      return {
        productListVisible: false,
        visible: false,
        display: false,
        addType: 0,
        fileList: [],
        dataList: [],
        id: 0,
        productDetails: [],
        dataForm: {},
        dataRule: {
          // contractNumber: [{ required: true, message: '合同号不能为空', trigger: 'blur' }],
          customerId: [{ required: true, message: '客户名称不能为空', trigger: 'change' }],
          salesmanId: [{ required: true, message: '业务员不能为空', trigger: 'change' }],
          deliveryDate: [{ required: true, message: '合同交期不能为空', trigger: 'change' }]
        },
        stepList: [],
        logList: []
      }
    },
    methods: {
      onChose () {
        this.$emit('onChose')
      },
      // 初始化：addType 新增类型： 0新增，1修改 2技术确认 (目前只有2才会赋值)
      async init (id, display, addType) {
        if (addType) {
          this.addType = addType
        }
        this.fileList = []
        this.stepList = []
        this.logList = []
        this.dataForm = {
          rateVal: 0
        }
        this.productDetails = []
        this.visible = true
        this.id = id || 0
        this.display = display
        if (!id) return
        await getOrderDetail(this.id).then(({data}) => {
          if (data && data.code === '200') {
            this.dataForm = data.data
            // 流程图展示
            dealStepData(data.data.workFlowBusinessExt.workFlowProcessStepList, this.stepList)
            dealStepLogs(data.data.workFlowBusinessExt.processLogList, this.logList)
            // 附件
            if (data.data.attachList) {
              data.data.attachList.forEach((item) => {
                this.fileList.push({
                  name: item.fileName,
                  url: item.url,
                  id: item.url
                })
              })
            }
            // 订单产品明细
            if (data.data.saleROrderProductList) {
              data.data.saleROrderProductList.forEach((item) => {
                this.addItem(item)
              })
            }
          }
        })
      },
      uploadSuccess (fileList) {
        this.fileList = fileList
      },
      addItem (item) {
        if (!item.recordId) {
          item.recordId = Math.round(Math.random() * 1000000)
        }
        if (this.productDetails.findIndex(item1 => item1.recordId === item.recordId) === -1) {
          this.productDetails.push({
            ...item
          })
        }
      },
      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
                })
              }
            }
            // 订单产品明细
            let pList = this.productDetails
            if (pList.length > 0) {
              this.dataForm.saleROrderProductParamsList = pList
              // // rate百分比转换
              // this.dataForm.saleROrderProductParamsList.forEach((item) => {
              //   item.rate = toNumber(item.rateVal)
              // })
            } else {
              this.$message.error('请添加订单产品明细')
              return
            }
            this.$http({
              url: !this.id ? this.$http.adornUrl(`/biz-service/order/save`) : this.$http.adornUrl(`/biz-service/order/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)
              }
            })
          }
        })
      },
      // 业务员选择变化
      salesmanChanged (val) {
        this.dataForm.salesmanId = val
      },
      // 添加订单产品明细
      addProduct () {
        this.productListVisible = true
        this.$nextTick(() => {
          this.$refs.productList.init(2)
        })
      },
      // 编辑产品项
      updateProductHandle (row) {
        this.productListVisible = true
        this.$nextTick(() => {
          this.$refs.productList.init(2, row, this.addType)
        })
      },
      // 删除产品项
      deleteProductHandle (recordId) {
        this.productDetails.splice(this.productDetails.findIndex((item) => item.recordId === recordId))
      }
    }
  }
</script>

<style scoped>

</style>
