<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="cusId">
            <el-select
              v-model="dataForm.cusId"
              :disabled="display"
              remote
              placeholder="请选择">
              <el-option
                v-for="item in optionsCus"
                :key="item.value"
                :label="item.customerName"
                :value="item.customerId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="padding-left: 20px">
          <el-form-item label="联系人" prop="name">
            <el-input v-model="dataForm.name" disabled placeholder="联系人"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="padding-left: 20px">
          <el-form-item label="沟通类别" prop="coType">
            <el-select
              v-model="dataForm.coType"
              :disabled="display"
              remote
              placeholder="请选择">
              <el-option
                v-for="item in options"
                :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="备注说明">
            <el-input v-model="dataForm.code" :disabled="display"></el-input>
          </el-form-item>
      </el-row>
      <el-row class="my-row">
        <div class="title"><span style="color: red">*</span> 沟通扫描件</div>
        <el-upload
          class="upload-demo"
          ref="upload"
          :multiple="true"
          action="#"
          accept="image/jpeg,image/gif,image/png"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-change="handleChange"
          :file-list="fileList"
          :limit="5"
          :on-exceed="handleExceed"
          :auto-upload="false">
          <el-button v-show="!display" slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button v-show="!display" style="margin-left: 10px;" size="small" type="success" @click="submitUpload">开始上传</el-button>
          <div v-show="!display" slot="tip" class="el-upload__tip">只能上传jpg/png文件，最多5张图片，且每张图片不超过10M</div>
        </el-upload>
      </el-row>
      <div class="title"><span style="color: red">*</span> 订单产品明细</div>
      <el-row>
        <el-table
          :data="cusRCommProductVOS"
          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"
            label="产品名称">
          </el-table-column>
          <el-table-column
            prop="cnt"
            header-align="center"
            align="center"
            label="数量"
            width="170">
            <template slot-scope="scope">
               <el-input-number v-model="scope.row.cnt" :disabled="display" :min="1" style="width: 140px;"/>
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            header-align="center"
            align="center"
            label="含税单价">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.price" :disabled="display" :precision="2" :step="0.1" :min="0" style="width: 140px;"/>
            </template>
          </el-table-column>
          <el-table-column
            prop="amount"
            header-align="center"
            align="center"
            label="含税总价">
            <template slot-scope="scope">
              <span>{{ (scope.row.cnt*scope.row.price).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="rate"
            header-align="center"
            align="center"
            label="税率">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.rate" :disabled="display">
                <template slot="append">%</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="notes"
            header-align="center"
            align="center"
            label="备注">
          </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="inBound"></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>
  <!-- 图片预览 -->
  <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
    <img :src="previewPath" :alt="previewName" style="width:100%;height:100%" />
  </el-dialog>
   <template-chose v-if="inboundVisible" ref="inbound" @addItem="addItem" />
</div>
</template>

<script>
  import templateChose from '../product/template-chose'
  import { getCustomer, getCoDetail } from '@/api/cus'
  import { uploadUrl, downloadUrl, uploadFiles } from '@/api/file'
  import { getDictList } from '@/api/dict'
  export default {
    name: 'communicate-add-or-update',
    components: {templateChose},
    computed: {
      orgId: {
        get () { return this.$store.state.user.orgId }
      }
    },
    data () {
      return {
        inboundVisible: false,
        visible: false,
        display: false,
        dictType: 'material_type',
        options: [],
        optionsCus: [],
        dataList: [],
        fileList: [],
        id: 0,
        cusRCommProductVOS: [],
        dataForm: {},
        dataRule: {
          cusId: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
          coType: [{ required: true, message: '沟通类别不能为空', trigger: 'change' }],
          name: [{ required: true, message: '联系人不能为空', trigger: 'blur' }]
        },
        uploadUrl: uploadUrl,
        previewPath: '',
        previewName: '',
        previewVisible: false
      }
    },
    watch: {
      'dataForm.cusId' (value) {
        this.optionsCus.forEach(v => {
          if (v.customerId === value) {
            this.dataForm.name = v.contact
          }
        })
      }
    },
    methods: {
      async init (id, display) {
        this.dataForm = {}
        this.cusRCommProductVOS = []
        this.visible = true
        this.id = id || 0
        this.display = display
        // 获取沟通类别
        await getDictList({type: 'communication_type'}).then(({data}) => {
          if (data) {
            this.options = data
          }
        })
        await getCustomer().then(({data}) => {
          if (data && data.code === '200') {
            this.optionsCus = data.data
          }
        })
        if (!id) return
        await getCoDetail(this.id).then(({data}) => {
          if (data && data.code === '200') {
            this.dataForm = data.data
            // 附件显示
            this.fileList = []
            data.data.attachList.forEach((item) => {
              this.fileList.push({
                name: item.fileName,
                url: item.url,
                id: item.url
              })
            })
            if (data.data.cusRCommProductVOS) {
              data.data.cusRCommProductVOS.forEach((item) => {
                this.cusRCommProductVOS.push({
                  cnt: item.cnt,
                  price: item.price,
                  productId: item.productId,
                  rate: item.rate,
                  productName: item.productName,
                  notes: item.notes
                })
              })
            }
          }
        })
      },
      submitUpload () {
        // this.$refs.upload.submit()
        if (this.fileList.length === 0) {
          return this.$message.warning('请选取文件后再上传')
        }
        const formData = new FormData()
        this.fileList.forEach((file) => {
          formData.append('file', file.raw)
        })
        uploadFiles(formData).then(({data}) => {
          if (data && data.code === '200') {
            data.data.forEach((item) => {
              let fileData = this.fileList.find((file) => file.name === item.originFileName)
              fileData.url = item.fileUrl
            })
            this.$message.success('上传成功')
          } else {
            this.$message.error('上传失败')
          }
        })
      },
      handleRemove (file, fileList) {
        this.fileList = fileList
      },
      handlePreview (file) {
        if (file && file.url) {
          // 获取文件路径
          this.previewPath = downloadUrl + file.url
          this.previewName = file.name
          this.previewVisible = true
        }
      },
      handleChange (file, fileList) {
        this.fileList = fileList
      },
      handleExceed (files, fileList) {
        this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 添加附件
            let fList = this.fileList
            // console.log('fileList = ' + fList)
            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
                })
              }
            }
            this.dataForm.cusRCommProductVOS = this.cusRCommProductVOS
            this.$http({
              url: this.$http.adornUrl(`/biz-service/cusCommunication/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)
              }
            })
          }
        })
      },
      validateField (type) {
        this.$refs.dataForm.validateField(type)
      },
      inBound () {
        this.inboundVisible = true
        this.$nextTick(() => {
          this.$refs.inbound.init()
        })
      },
      addItem (item) {
        this.cusRCommProductVOS.push({
          cnt: 1,
          price: 0,
          productId: item.productId,
          rate: 0,
          productName: item.productName,
          notes: item.notes
        })
      }
    }
  }
</script>

<style scoped>
.my-line{
  border-bottom: 1px solid #c0c4cc;
  margin-bottom: 10px;
}
.title{
  padding: 10px 0 ;
}
</style>
