<template>
  <div class="container">
    <el-form ref="elForm" :model="formData" :rules="rules" size="mini" label-width="100px">
      <el-form-item v-if="false" label="报价单Id" prop="quotId">
        <el-input v-model="formData.quotId" placeholder="报价单Id" readonly clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="报价单单号" prop="quotCode">
        <el-input v-model="formData.quotCode" placeholder="报价单单号(自动生成)" readonly clearable
                  ></el-input>
      </el-form-item>
      <el-form-item label="客户" prop="quotCustomerName">
        <el-input readonly v-model="formData.quotCustomerName" placeholder="请输入客户" >
          <template slot="append">
            <span @click="openCustomer">选择</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="地址" prop="quotAddress">
        <el-input v-model="formData.quotAddress" placeholder="请输入地址" clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="审核人" prop="quotCheckUserNickname">
        <el-input readonly v-model="formData.quotCheckUserNickname" placeholder="审核人" clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="提交状态" prop="quotApprovalStatus">
        <el-input readonly v-model="formData.quotApprovalStatus" placeholder="保存后显示" clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="项目名称" prop="quotProject">
        <el-input v-model="formData.quotProject" placeholder="请输入项目名称" clearable >
        </el-input>
      </el-form-item>
      <el-form-item label="报价要求" prop="quotQuotationRequire">
        <el-input v-model="formData.quotQuotationRequire" placeholder="请输入报价要求" clearable
                  ></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="quotPhone">
        <el-input v-model="formData.quotPhone" placeholder="请输入联系电话" clearable >
        </el-input>
      </el-form-item>


      <el-divider content-position="left" class="customer_divider_text">询价附件(先保存)</el-divider>
      <div v-hasPermi="['quot:quot:quotXjFile']">
        <el-upload class="upload-demo"
                   ref="upload"
                   name="quotFile"
                   :action="uploadUrl"
                   :headers="headers"
                   :data="{ relation_id: this.formData.quotId,file_type: 'quotXjFile' }"
                   :on-success="handleAvatarSuccess"
                   :show-file-list="false"
                   :limit="1"
                   v-if="this.formData.quotApprovalStatus == 0">
          <el-button size="small" type="primary" @click="uploadFile('quotXjFile')">上传文件</el-button>
        </el-upload>
      </div>
      <el-table class="down" :data="quotXjFileList" border stripe style="width: 100%;margin-top: 10px;" height="200px">
        <el-table-column prop="fileName" label="文件名称" ></el-table-column>
        <el-table-column width="150px" label="操作">
          <template slot-scope="scope">
            <el-button :key="Math.random()" size="small" type="text">
              <a @click="downloadFile(scope.row.fileUrl)">下载</a>
            </el-button>
            <el-button :key="Math.random()" size="small" type="text" v-if="formData.quotApprovalStatus == 0">
              <a @click="deleteFile(scope.row.fileId,'quotXjFile')">删除</a>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-divider content-position="left" class="customer_divider_text">技术规范要求(询价附件)</el-divider>
      <div v-hasPermi="['quot:quot:quotXjFile']">
        <el-upload class="upload-demo"
                   ref="upload"
                   name="quotFile"
                   :action="uploadUrl"
                   :headers="headers"
                   :data="{ relation_id: this.formData.quotId,file_type: 'quotXjFile' }"
                   :on-success="handleAvatarSuccess"
                   :show-file-list="false"
                   :limit="1"
                   v-if="this.formData.quotApprovalStatus === '0'">
          <el-button size="small" type="primary" @click="uploadFile('quotXjFile')">上传文件</el-button>
        </el-upload>
      </div>
      <el-table class="down" :data="quotXjFileList" border stripe style="width: 100%;margin-top: 10px;" height="200px">
        <el-table-column prop="fileName" label="文件名称" ></el-table-column>
        <el-table-column width="150px" label="操作">
          <template slot-scope="scope">
            <el-button :key="Math.random()" size="small" type="text">
              <a @click="downloadFile(scope.row.fileUrl)">下载</a>
            </el-button>
            <el-button :key="Math.random()" size="small" type="text" v-if="formData.quotApprovalStatus == '0'">
              <a @click="deleteFile(scope.row.fileId,'quotXjFile')">删除</a>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-divider content-position="left" class="customer_divider_text">反馈附件</el-divider>
      <div v-hasPermi="['quot:quot:quotXjFile']">
        <el-upload class="upload-demo"
                   ref="upload"
                   name="quotFile"
                   :action="uploadUrl"
                   :headers="headers"
                   :data="{ relation_id: this.formData.quotId,file_type: 'quotXjFile' }"
                   :on-success="handleAvatarSuccess"
                   :show-file-list="false"
                   :limit="1"
                   v-if="this.formData.quotApprovalStatus == '0'">
          <el-button size="small" type="primary" @click="uploadFile('quotXjFile')">上传文件</el-button>
        </el-upload>
      </div>
      <el-table class="down" :data="quotXjFileList" border stripe style="width: 100%;margin-top: 10px;" height="200px">
        <el-table-column prop="fileName" label="文件名称" ></el-table-column>
        <el-table-column width="150px" label="操作">
          <template slot-scope="scope">
            <el-button :key="Math.random()" size="small" type="text">
              <a @click="downloadFile(scope.row.fileUrl)">下载</a>
            </el-button>
            <el-button :key="Math.random()" size="small" type="text" v-if="formData.quotApprovalStatus == '0'">
              <a @click="deleteFile(scope.row.fileId,'quotXjFile')">删除</a>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-form-item style="margin-top: 15px">
        <el-button  @click="saveForm">保存</el-button>
        <el-button style="margin: 0px 15px 0px 20px" type="primary" @click="submitForm">提交</el-button>
        <el-button  @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <CustomerSelect :width="100 + '%'" ref="customerSelect" :open="customerOpen" @submit="submitCustomer" @cancel="customerOpen=false"></CustomerSelect>
  </div>
</template>
<script>
import CustomerSelect from "@/views/components/Tools/Mobile/CustomerSelect/index.vue";
import { NumberAdd }  from '@/utils/number';// 数值计算
import { changQuotPrintStatus,listQuot, getQuot, getReturnUpdateQuot, delQuot, addQuot, updateQuot, quotFileList, quotFileDelete, commitQuot, commitJsQuot, commitHjQuot, commitJswQuot, commitOAQuot, feedbackQuot, madeQuot, rejectQuot } from "@/api/quot/quot";
import { getToken } from "@/utils/auth";
import { checkPermi,checkRole } from '@/utils/permission';// 权限判断函数
import { getDicts } from "@/api/system/dict/data";

/** 导入技术确认单详情组件*/
import jsqrDialog from '@/views/technicalConfirm/technicalConfirm/jsxzInfo.vue';
/** 导入核价单详情组件*/
import hjDialog from '@/views/priceVerification/priceVerification/hjInfo.vue';
/** 导入选人组件 */
import PeopleSelect from "@/views/components/Tools/PeopleSelect/index.vue";

/** 弹窗放大、拖拽 */
import elDragDialog from "@/directive/dialog/dragDialog";

export default {
  components: {
    // 注册组件
    'CustomerSelect': CustomerSelect,
  },
  props: [],
  data() {
    return {
      // 表单参数
      form: {},
      // 报价单-询价附件列表数据
      quotXjFileLoading: false,
      quotXjFileList: [],
      // 报价单-反馈附件列表数据
      quotFkFileLoading: false,
      quotFkFileList: [],
      // 报价单-技术规范附件列表数据
      quotJsgfFileLoading: false,
      quotJsgfFileList: [],
      //报价单-询价附件上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/quot/quot/quotFile",
      //报价单-询价附件请求头
      headers: {Authorization: "Bearer " + getToken()},
      // 技术协助附件表格数据
      quotJsqrFileList: [],
      quotJsqrTlFileNum: 0,
      quotJsqrDyFileNum: 0,
      quotJsqrZyFileNum: 0,
      quotJsqrQtFileNum: 0,
      //是否打开客户选择组件，默认不打开
      customerOpen:false,
      formData: {
        quotId: null,
        quotCode: '',
        quotCustomerName: '',
        quotAddress: '',
        quotCheckUserNickname: '',
        quotProject: '',
        quotQuotationRequire: '',
        quotPhone: '',
        quotQuotationFrom: '',
        quotPrintUserName: '',
        field115: null,
        field116: null,
      },
      rules: {
        quotAddress: [{
          required: true,
          message: '请输入地址',
          trigger: 'blur'
        }],
        quotProject: [{
          required: true,
          message: '请输入项目名称',
          trigger: 'blur'
        }],
        quotQuotationRequire: [{
          required: true,
          message: '请输入报价要求',
          trigger: 'blur'
        }],
        quotPhone: [{
          required: true,
          message: '请输入联系电话',
          trigger: 'blur'
        }],
        quotQuotationFrom: [{
          required: true,
          message: '请输入报价来源',
          trigger: 'blur'
        }],
      },
      field115Action: 'https://jsonplaceholder.typicode.com/posts/',
      field115fileList: [],
      field116Action: 'https://jsonplaceholder.typicode.com/posts/',
      field116fileList: [],

    }
  },
  computed: {},
  watch: {},
  created() {
    const quotId = this.$route.params && this.$route.params.quotId;
    if (quotId !== undefined && quotId !== null) {
      const row = {'quotId':quotId}
      this.handleUpdate(row);
    }

    console.log(quotId);
  },
  mounted() {},
  methods: {
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        // TODO 提交表单
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    field115BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    field116BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 100
      if (!isRightSize) {
        this.$message.error('文件大小超过 100MB')
      }
      return isRightSize
    },
    //打开客户选择弹窗
    openCustomer(){
      this.customerOpen=true;
    },
    //客户选择确定按钮事件
    submitCustomer(customer){
      this.formData.quotCustomerName = customer.label
      this.customerOpen=false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const quotId = row.quotId || this.ids
      getQuot(quotId).then(response => {
        this.setInfo(response);
      });
    },
    /** 修改按钮操作-详细信息设置 */
    setInfo(response){
      console.log(response)
      this.formData = response.data;
      this.$set(this.formData, "quotJsxzGroup", (this.formData.quotJsxzGroupValues==''||this.formData.quotJsxzGroupValues==null)?[]:this.formData.quotJsxzGroupValues.split(','));
      this.open = true;
      this.activeName = "quotInfo";

      const quotJsxzGroup = this.form.quotJsxzGroupValues;
      if(quotJsxzGroup){
        if(quotJsxzGroup.indexOf("TL")!==-1){
          this.showTl = true;
          this.getQuotJsqrFileList('quotJsqrTlFkFile');
        }
        if(quotJsxzGroup.indexOf("DY")!==-1){
          this.showDy = true;
          this.getQuotJsqrFileList('quotJsqrDyFkFile');
        }
        if(quotJsxzGroup.indexOf("ZY")!==-1){
          this.showZy = true;
          this.getQuotJsqrFileList('quotJsqrZyFkFile');
        }
        if(quotJsxzGroup.indexOf("QT")!==-1){
          this.showQt = true;
          this.getQuotJsqrFileList('quotJsqrQtFkFile');
        }
      }
      this.getQuotXjFileList();
      this.getQuotJsgfFileList();
      this.getQuotHjFileList();
      this.getQuotFkFileList();
    },

    /** 保存按钮 */
    saveForm() {
      this.$refs["elForm"].validate(valid => {
        if (valid) {
          if (this.formData.quotId != null) {
            updateQuot(this.formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
            });
          } else {
            addQuot(this.formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              const row = {'quotId':response.data.quotId}
              this.handleUpdate(row);
            }) ;
          }
        }
      });
    },

    /*********************************附件列表数据展示、上传*****************************************/
    //获取报价单-询价附件列表
    getQuotXjFileList(){
      const param = {relationId:this.form.quotId,fileType:'quotXjFile'}
      quotFileList(param).then(response => {
        this.quotXjFileList = response.rows;
      });
    },
    //获取报价单-反馈附件列表
    getQuotFkFileList(){
      const param = {relationId:this.form.quotId,fileType:'quotFkFile'}

      //协助中状态不显示反馈附件
      if(this.form.quotApprovalStatus!='1' && checkRole(['SALES_MAN'])){
        quotFileList(param).then(response => {
          this.quotFkFileList = response.rows;
        });
      }else if(checkRole(['QUOT'])){
        quotFileList(param).then(response => {
          this.quotFkFileList = response.rows;
        });
      }
    },
    //获取报价单-技术规范附件列表
    getQuotJsgfFileList(){
      console.log(this.form.quotId)
      const param = {relationId:this.form.quotId,fileType:'quotJsgfFile'}
      quotFileList(param).then(response => {
        this.quotJsgfFileList = response.rows;
      });
    },
    //获取报价单-技术确认-反馈附件上传
    getQuotJsqrFileList(fileType){
      const param = {relationId:this.form.quotJsxzConfirmId,fileType:fileType}
      quotFileList(param).then(response => {
        this.quotJsqrFileList = response.rows;
        if('quotJsqrTlFkFile' == fileType){
          this.quotJsqrTlFileNum = response.rows.length;
        }else if('quotJsqrDyFkFile' == fileType){
          this.quotJsqrDyFileNum = response.rows.length;
        }else if('quotJsqrZyFkFile' == fileType){
          this.quotJsqrZyFileNum = response.rows.length;
        }else if('quotJsqrQtFkFile' == fileType){
          this.quotJsqrQtFileNum = response.rows.length;
        }
      });
    },
    //获取报价单-核价附件列表
    getQuotHjFileList(){
      const param = {relationId:this.form.quotHjId,fileType:'quotHjFile'}
      quotFileList(param).then(response => {
        this.quotHjFileList = response.rows;
      });
    },
    //特缆、低压、中压、其他 反馈附件显示窗口
    handleAddFile(group){
      this.addFileOpen = true;
      this.quotJsqrFileList = [];
      if("quotJsqrTl"==group){
        this.addFileTitle = '特缆反馈附件'
        this.fileType = 'quotJsqrTlFkFile';
        this.uploadDis = (this.form.quotJsqrTlOperateState == 0 ? true : false);
      }else if('quotJsqrDy'==group){
        this.addFileTitle = '低压反馈附件'
        this.fileType = 'quotJsqrDyFkFile';
        this.uploadDis = (this.form.quotJsqrDyOperateState == 0 ? true : false);
      }else if('quotJsqrZy'==group){
        this.addFileTitle = '中压反馈附件'
        this.fileType = 'quotJsqrZyFkFile';
        this.uploadDis = (this.form.quotJsqrZyOperateState == 0 ? true : false);
      }else if('quotJsqrQt'==group){
        this.addFileTitle = '其他反馈附件'
        this.fileType = 'quotJsqrQtFkFile';
        this.uploadDis = (this.form.quotJsqrQtOperateState == 0 ? true : false);
      }
      // 获取反馈附件
      this.getQuotJsqrFileList(this.fileType);
    },

    //点击上传附件按钮触发事件
    uploadFile(activeName){
      this.activeName = activeName
    },
    //上传前校验-反馈附件
    beforeAvatarUploadQuotFkFile(file) {
      this.quotFkFileLoading = true;
    },
    //上传前校验-清单附件
    beforeAvatarUploadQuotXjFile(file) {
      this.quotXjFileLoading = true;
      let activeName = this.activeName;
      if(activeName=='quotXjFile'){
        if(file.name.split('.')[1].toLowerCase() != 'xls' && file.name.split('.')[1].toLowerCase() != 'xlsx'){
          this.$modal.msgError("清单附件必须是Excel格式");
          this.quotXjFileLoading = false;
          return false;
        }
      }
    },
    //上传前校验-清单附件
    beforeAvatarUploadQuotJsgfFile(file){
      this.quotJsgfFileLoading = true;
      const maxSize = 100 * 1024 * 1024; // 100MB，根据你的需求设置最大文件大小
      if (file.size > maxSize) {
        this.$modal.msgError("文件大小超过了"+maxSize / (1024 * 1024)+"MB的限制");
        this.quotJsgfFileLoading = false;
        return false;
      }
    },
    //成功回调
    handleAvatarSuccess(res) {
      let activeName = this.activeName;
      // 如果上传成功
      if (res.code == 200) {
        this.$modal.msgSuccess(res.msg);
        if(activeName=='quotXjFile'){
          this.getQuotXjFileList();
          this.quotXjFileLoading = false;
          this.$refs.quotXjFileUpload.clearFiles(); //上传成功之后清除历史记录**加粗样式**
        }else if(activeName=='quotJsgfFile'){
          this.getQuotJsgfFileList();
          this.quotJsgfFileLoading = false;
          this.$refs.quotJsgfFileUpload.clearFiles(); //上传成功之后清除历史记录**加粗样式**
        }else if(activeName=='quotFkFile'){
          this.getQuotFkFileList();
          this.quotFkFileLoading = false;
          this.$refs.quotFkFileUpload.clearFiles(); //上传成功之后清除历史记录**加粗样式**
        }
      } else {
        this.$modal.msgError(res.msg);
        if(activeName=='quotXjFile'){
          this.quotXjFileLoading = false;
          this.$refs.quotXjFileUpload.clearFiles(); //上传成功之后清除历史记录**加粗样式**
        }else if(activeName=='quotJsgfFile'){
          this.quotJsgfFileLoading = false;
          this.$refs.quotJsgfFileUpload.clearFiles(); //上传成功之后清除历史记录**加粗样式**
        }else if(activeName=='quotFkFile'){
          this.quotFkFileLoading = false;
          this.$refs.quotFkFileUpload.clearFiles(); //上传成功之后清除历史记录**加粗样式**
        }
      }
    },

    /** 产品数据文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.productUpload.open = false;
      this.productUpload.isUploading = false;
      this.$refs.productUpload.clearFiles();
      this.$message.success("产品数据导入成功!");
      this.quotMaterialList = this.quotMaterialList.concat(response.data)
    },
    //下载附件
    downloadFile(fileUrl){
      window.open(fileUrl, "_blank");
    },

    //删除附件
    deleteFile(fileId,activeName){
      if(activeName=='quotXjFile'){
        this.quotXjFileLoading = true;
        quotFileDelete(fileId).then(response => {
          this.getQuotXjFileList();
          this.quotXjFileLoading = false;
        })
      }else if(activeName=='quotJsgfFile'){
        this.quotJsgfFileLoading = true;
        quotFileDelete(fileId).then(response => {
          this.getQuotJsgfFileList();
          this.quotJsgfFileLoading = false;
        })
      }else if(activeName=='quotFkFile'){
        this.quotFkFileLoading = true;
        quotFileDelete(fileId).then(response => {
          this.getQuotFkFileList();
          this.quotFkFileLoading = false;
        })
      }
    },
  },

}

</script>
<style>
.small-upload .el-upload {

  width: 100px;
  height: 100px;
}

.el-upload__tip {
  line-height: 1.2;
}

.container {
  margin: 20px;
}

</style>
