<template>
  <div>
    <div class="my-title">{{ !id ? "新增" : display ? "详情" : "修改" }}</div>
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="auto"
    >
      <el-row class="my-row">
        <el-col :span="6">
          <el-form-item label="客户名称" prop="cusId">
            <el-select
              v-model="dataForm.cusId"
              :disabled="display"
              remote
              placeholder="请选择"
              style="width: 100%"
            >
              <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="6">
          <el-form-item label="客户联系人" prop="contact">
            <el-input
              v-model="dataForm.contact"
              disabled
              placeholder="联系人"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话" prop="contactTel">
            <el-input v-model="dataForm.contactTel" placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="沟通方式" prop="way">
            <el-input v-model="dataForm.way" placeholder=""></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="my-row">
        <el-col :span="6">
          <el-form-item label="沟通类别" prop="coType">
            <el-select
              v-model="dataForm.coType"
              :disabled="display"
              remote
              @change="typeChanged"
              placeholder="请选择"
              style="width: 100%"
            >
              <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-col :span="12">
          <el-form-item label="沟通主要内容" prop="content">
            <el-input
              v-model="dataForm.content"
              :disabled="display"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input
              v-model="dataForm.notes"
              :disabled="display"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="my-row">
        <el-col :span="8">
          <el-form-item label="技术资料" prop="attachListTechnical">
            <upload-component
              :display="display"
              :displayStar="false"
              :accept="'*'"
              v-model="dataForm.attachListTechnical"
              @uploadSuccess="uploadSuccessTechnical"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="4">
          <el-form-item label="数模/图纸" prop="attachListDrawing">
            <upload-component
              :display="display"
              :displayStar="false"
              :accept="'*'"
              v-model="dataForm.attachListDrawing"
              @uploadSuccess="uploadSuccessDrawing"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="my-row">
        <el-col :span="8">
          <el-form-item label="沟通表原件" prop="attachList">
            <upload-component
              :display="display"
              :displayStar="false"
              :accept="'*'"
              v-model="dataForm.attachList"
              @uploadSuccess="uploadSuccess"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="4">
          <el-form-item label="其他附件" prop="attachListOther">
            <upload-component
              :display="display"
              :displayStar="false"
              :accept="'*'"
              v-model="dataForm.attachListOther"
              @uploadSuccess="uploadSuccessOther"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <div class="title">沟通物料明细</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"
              min-width="120"
              :show-tooltip-when-overflow="true"
              label="物料名称"
            >
            </el-table-column>
            <el-table-column
              prop="productSpecifications"
              header-align="center"
              align="center"
              :show-tooltip-when-overflow="true"
              label="规格"
            >
            </el-table-column>
            <el-table-column
              prop="cnt"
              header-align="center"
              align="center"
              label="数量"
            >
            </el-table-column>
            <el-table-column
              prop="deliveryDate"
              header-align="center"
              align="center"
              min-width="100"
              width="150"
              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"
              min-width="180"
              :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>
        <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>
      </div>
      <div>
        <div class="title">任务工单派发</div>
        <el-row>
          <el-table :data="workInfoList" border style="width: 100%">
            <el-table-column
              label="序号"
              type="index"
              width="50"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="taskType"
              header-align="center"
              align="center"
              min-width="100"
              width="120"
              label="工单类型"
            >
              <template slot-scope="scope">
                <span>{{
                taskTypeOption.findIndex((t) => t.value == scope.row.taskType) > -1
                ? taskTypeOption.find((t) => t.value == scope.row.taskType).label
                : ''
              }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="taskName"
              header-align="center"
              align="center"
              :show-tooltip-when-overflow="true"
              label="工单名称"
            >
            </el-table-column>
            <el-table-column
              prop="ranks"
              header-align="center"
              align="center"
              width="120"
              label="级别"
            >
              <template slot-scope="scope">
                 <span>{{
                rankTypeOption.findIndex((t) => t.value == scope.row.ranks) > -1
                ? rankTypeOption.find((t) => t.value == scope.row.ranks).label
                : ''
              }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="content"
              header-align="center"
              align="center"
              min-width="100"
              label="工单内容"
              :show-tooltip-when-overflow="true"
            >
            </el-table-column>
            <el-table-column
              prop="receiver"
              header-align="center"
              align="center"
              width="150"
              label="任务接收人"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.receiverName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="attachListVo"
              header-align="center"
              align="center"
              width="150"
              label="任务附件"
            >
              <template slot-scope="scope">
                <el-button
                  :disabled="
                    !scope.row.attachListVo || scope.row.attachListVo.length === 0
                  "
                  type="text"
                  size="small"
                  @click="attachDetails(scope.row.attachListVo)"
                  >查看</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="notes"
              header-align="center"
              align="center"
              :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="updateWorderHandle(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>
        <el-row v-if="!display" style="text-align: center; margin-top: 10px">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="worderAdd"
          ></el-button>
        </el-row>
      </div>
    </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>
    <add-or-update v-if="inboundVisible" ref="inbound" @addItem="addItem" />
    <worder-add-or-update-dialog
      v-if="worderVisible"
      ref="worder"
      @submit="addWorderItem"
    />
    <attach-detail-dialog ref="attachDetail" @onChose="onChose" />
  </div>
</template>

<script>
// import templateChose from '../product/template-chose'
import { getCustomer, getCoDetail } from '@/api/cus'
import { getDictList } from '@/api/dict'
import uploadComponent from '../common/upload-component-v2'
import AddOrUpdate from '../product/template-add-or-update-v2'
import WorderAddOrUpdateDialog from '../worder/add-or-update-dialog'
import AttachDetailDialog from '../common/attach-detail-dialog'
import { taskTypeOption, rankTypeOption } from '@/utils/enums'
export default {
  name: 'communicate-add-or-update',
  components: {
    AddOrUpdate,
    uploadComponent,
    WorderAddOrUpdateDialog,
    AttachDetailDialog
  },
  computed: {
    orgId: {
      get () {
        return this.$store.state.user.orgId
      }
    }
  },
  data () {
    return {
      inboundVisible: false,
      detailVisible: false,
      worderVisible: false,
      attachVisible: false,
      visible: false,
      display: false,
      dictType: 'material_type',
      options: [],
      optionsCus: [],
      dataList: [],
      attachListTechnical: [], // 技术资料
      attachListDrawing: [], // 数模/图纸
      attachList: [], // 沟通表原件
      attachListOther: [], // 其他附件
      id: 0,
      cusRCommProductVOS: [],
      workInfoList: [],
      dataForm: {},
      taskTypeOption: taskTypeOption,
      rankTypeOption: rankTypeOption,
      dataRule: {
        cusId: [
          { required: true, message: '客户名称不能为空', trigger: 'blur' }
        ],
        coType: [
          { required: true, message: '沟通类别不能为空', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        contactTel: [
          { required: true, message: '联系电话不能为空', trigger: 'blur' }
        ],
        way: [{ required: true, message: '沟通方式不能为空', trigger: 'blur' }],
        content: [
          { required: true, message: '沟通内容不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'dataForm.cusId' (value) {
      this.optionsCus.forEach((v) => {
        if (v.customerId === value) {
          this.dataForm.contact = v.contact
          this.dataForm.contactTel = v.contactTel
        }
      })
    }
  },
  methods: {
    onChose () {
      this.$emit('onChose')
      this.inboundVisible = false
      this.detailVisible = false
      this.worderVisible = false
      this.attachVisible = false
    },
    async init (id, display) {
      this.dataForm = {}
      this.cusRCommProductVOS = []
      this.workInfoList = []
      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
      this.detailVisible = true
      await getCoDetail(this.id).then(({ data }) => {
        if (data && data.code === '200') {
          this.dataForm = data.data
          if (this.dataForm.coType !== '1') {
            this.detailVisible = false
          }
          // 附件显示
          if (this.dataForm.attachListTechnical) {
            this.dataForm.attachListTechnical.forEach((item) => {
              item.name = item.fileName
              item.id = item.url
            })
          }
          if (this.dataForm.attachListDrawing) {
            this.dataForm.attachListDrawing.forEach((item) => {
              item.name = item.fileName
              item.id = item.url
            })
          }
          if (this.dataForm.attachList) {
            this.dataForm.attachList.forEach((item) => {
              item.name = item.fileName
              item.id = item.url
            })
          }
          if (this.dataForm.attachListOther) {
            this.dataForm.attachListOther.forEach((item) => {
              item.name = item.fileName
              item.id = item.url
            })
          }
          if (data.data.cusRCommProductVOS) {
            data.data.cusRCommProductVOS.forEach((item) => {
              this.addItem(item)
            })
          }
          if (data.data.workInfoList) {
            data.data.workInfoList.forEach((item) => {
              this.addWorderItem(item)
            })
          }
        }
      })
    },
    // 表单提交
    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,
          //     });
          //   }
          // } else {
          //   this.$message.error("请上传文件");
          //   return;
          // }
          // if (this.dataForm.coType === "1") {
          //   if (this.cusRCommProductVOS.length === 0) {
          //     this.$message.error("请选择任务单物料明细");
          //     return;
          //   }
          // }
          this.dataForm.cusRCommProductVOS = this.cusRCommProductVOS
          this.dataForm.workInfoList = this.workInfoList
          this.$http({
            url: !this.id
              ? this.$http.adornUrl(`/biz-service/cusCommunication/save`)
              : this.$http.adornUrl(`/biz-service/cusCommunication/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)
            }
          })
        }
      })
    },
    validateField (type) {
      this.$refs.dataForm.validateField(type)
    },
    inBound () {
      this.inboundVisible = true
      this.$nextTick(() => {
        this.$refs.inbound.init(1)
      })
    },
    // 编辑物料项
    updateProductHandle (row) {
      this.inboundVisible = true
      this.$nextTick(() => {
        this.$refs.inbound.init(1, row)
      })
    },
    addItem (item) {
      if (!item.recordId) {
        item.recordId = Math.round(Math.random() * 1000000)
      }
      if (
        this.cusRCommProductVOS.findIndex(
          (item1) => item1.recordId === item.recordId
        ) === -1
      ) {
        this.cusRCommProductVOS.push({
          ...item
        })
      }
    },
    // 添加工单
    addWorderItem (item) {
      if (!item.recordId) {
        item.recordId = Math.round(Math.random() * 1000000)
      }
      if (
        this.workInfoList.findIndex(
          (item1) => item1.recordId === item.recordId
        ) === -1
      ) {
        this.workInfoList.push({ ...item })
      }
    },
    uploadSuccessTechnical (fileList) {
      this.attachListTechnical = fileList
    },
    uploadSuccessDrawing (fileList) {
      this.attachListDrawing = fileList
    },
    uploadSuccess (fileList) {
      this.attachList = fileList
    },
    uploadSuccessOther (fileList) {
      this.attachListOther = fileList
    },
    typeChanged (item) {
      this.detailVisible = item === '1'
    },
    // 删除物料项
    deleteProductHandle (recordId) {
      this.cusRCommProductVOS.splice(
        this.cusRCommProductVOS.findIndex((item) => item.recordId === recordId),
        1
      )
    },
    worderAdd () {
      this.worderVisible = true
      this.$nextTick(() => {
        this.$refs.worder.init(0, null, 'addItem')
      })
    },
    updateWorderHandle (row) {
      this.worderVisible = true
      row.attachList = row.attachListVo
      this.$nextTick(() => {
        this.$refs.worder.init(1, row)
      })
    },
    attachDetails (attachList) {
      // attachList.forEach((item) => {
      //   item.fileName = item.name
      // })
      this.$refs.attachDetail.init(attachList)
    }
  }
}
</script>

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