<template>
  <div class="system-user">
    <!-- 头部细节部分 -->
      <div class="title">
        <el-row>
          <el-col :span="24">
            <div class="top">
              <el-input  placeholder="企业名称" class="input-demo" v-model="companyName"></el-input>
              <el-input  placeholder="经办人姓名" class="input-demo" v-model="operatorName"></el-input>
              <el-button type="success" style="margin-left: 1%;" @click="firstLoadData">查询</el-button>
              <el-button type="success" style="margin-left: 1%;" @click="addOperatorList = true">添加经办人</el-button>
              <el-button type="info" style="margin-left: 1%;" @click="addEditEmailList = true">更新备案邮箱</el-button>
              <el-button type="primary" style="margin-left: 1%;" @click="exportExcel">导出报表</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    <!-- 头部细节部分结束 -->
    <!-- 表格部分 -->
      <template>
        <el-table
         class="table"
          v-loading="loading"
          ref="multipleTable"
          :data="customerCompanytable"
           :height="heightt"
          border
          tooltip-effect="dark">
          <el-table-column
            label="企业名称"
            prop="companyName"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="企业编码"
            prop="companyNum"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="经办人姓名"
            prop="operatorName"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="经办人手机号"
            prop="operatorMobile"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
           label="经办人身份证"
           prop="identificationId"
           show-overflow-tooltip>
           </el-table-column>
           <el-table-column
            label="经办人附件名称"
            prop="contractFileName"
            show-overflow-tooltip>
          </el-table-column>
         <el-table-column
            label="证明附件名称"
            prop="operatorEvidenceContractFileName"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="状态"
            show-overflow-tooltip>
             <template slot-scope="scope">
               <span v-if="scope.row.status == 1" style="color:green">变更经办人短信确认成功</span>
              <span v-else-if="scope.row.status == 2" style="color: red">变更经办人发送短信</span>
              <span v-else-if="scope.row.status == 3" style="color: blue">经办人提交成功</span>
              <span v-else-if="scope.row.status == 4" style="color: cyan">证明附件上传成功</span>
              <span v-else-if="scope.row.status == 5" style="color: cyan">开票经办人短信发送</span>
              <span v-else-if="scope.row.status == 6" style="color: cyan">开票经办人认证成功</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="100">
            <template slot-scope="scope" show-overflow-tooltip>
              <el-link style="cursor:pointer;color: blue;" @click="openChange(scope.row)">证明附件</el-link>
            </template>
          </el-table-column>
          <el-table-column
            label="开票短信确认时间"
            prop="lastTime"
            width="180"
            show-overflow-tooltip>
          </el-table-column>
        </el-table>
    </template>
    <!-- 分页 -->
      <div class="block">
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[6, 8, 10, 20, 50 ,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
      </div>

    <!-- 新增企业开票经办人 -->
      <el-dialog
        @close="handleEditDialogClose"
        :visible.sync="addOperatorList"
        style="font-size: 0px;">
        <div class="tou">企业开票经办人--添加</div>
        <div class="line"></div>
        <el-form
          label-position="right"
          label-width="120px"
          :rules="rules"
          ref="ruleForm"
          :model="formOperatorList">
          <el-form-item label="企业名称" prop="companyName">
            <el-select v-model="formOperatorList.companyName"  @change="changeRow" filterable placeholder="请选择企业名称" style="width: 100%">
              <el-option
                v-for="item in comPanyNumList"
                :key="item.companyName"
                :label="item.companyName"
                :value="item.companyName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业编码" prop="companyNum">
            <el-input v-model="formOperatorList.companyNum" placeholder="企业编码" auto-complete="off" :disabled="true" ></el-input>
          </el-form-item>

         <el-form-item label="经办人姓名" prop="operatorName">
            <el-input v-model="formOperatorList.operatorName" auto-complete="off" placeholder="请输入经办人姓名"></el-input>
          </el-form-item>

         <el-form-item label="经办人手机号" prop="operatorMobile">
            <el-input v-model="formOperatorList.operatorMobile" auto-complete="off" placeholder="请输入经办人手机号"></el-input>
          </el-form-item>

         <el-form-item label="经办人身份证" prop="identificationId">
            <el-input v-model="formOperatorList.identificationId" auto-complete="off" placeholder="请输入经办人身份证"></el-input>
          </el-form-item>
         <el-form-item  label-width=120px label="协议文件名" v-show= false>
              <el-input v-model="formOperatorList.contractFileName" auto-complete="off" :disabled=disable ></el-input>
        </el-form-item>
        <el-form-item  label-width=120px label="上传营业执照" prop="contractFileName">
              <el-upload
                  class="avatar-uploader"
                  style="width: 100%"
                  action="#"
                  :show-file-list="false"
                  :http-request="httpRequest">
                    <el-input label-width=120px v-model="formOperatorList.contractFileName" auto-complete="off"  style="width: 100%"></el-input>
                    <!-- <el-button type="primary" @click="getFile(index)">选取文件</el-button> -->
                </el-upload>
                <el-input label-width=120px v-model="formOperatorList.base64Str" v-show="false" auto-complete="off"></el-input>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addOperatorList = false" type="info">取 消</el-button>
          <el-button type="primary" @click="addData('ruleForm')">新 增</el-button>
        </div>
      </el-dialog>


 <!-- 更新邮箱 -->
      <el-dialog
        @close="handleEditDialogClose"
        :visible.sync="addEditEmailList"
        style="font-size: 0px;">
        <div class="tou">更新备案邮箱--添加</div>
        <div class="line"></div>
        <el-form
          label-position="right"
          label-width="120px"
          :rules="ruleEmails"
          ref="ruleEmailForm"
          :model="formEditEmailList">


          <el-form-item label="企业名称" prop="companyName">
            <el-select v-model="formEditEmailList.companyName"  @change="changeRowEditEmail" filterable placeholder="请选择企业名称" style="width: 100%">
              <el-option
                v-for="item in comPanyNumList"
                :key="item.companyName"
                :label="item.companyName"
                :value="item.companyName">
              </el-option>
            </el-select>
          </el-form-item>
           <el-form-item label="客户号" prop="customerName">
                      <el-input v-model="formEditEmailList.customerName"  placeholder="客户号" auto-complete="off" :disabled="true"></el-input>
                    </el-form-item>
          <el-form-item label="企业编码" prop="companyNum">
            <el-input v-model="formEditEmailList.companyNum" placeholder="企业编码" auto-complete="off" :disabled="true" ></el-input>
          </el-form-item>

         <el-form-item label="邮箱" prop="invoiceMail">
            <el-input v-model="formEditEmailList.invoiceMail" auto-complete="off" placeholder="请输入邮箱"></el-input>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addEditEmailList = false" type="info">取 消</el-button>
          <el-button type="primary" @click="editEmail('ruleEmailForm')">更 新</el-button>
        </div>
      </el-dialog>


       <el-dialog
           @close="handleEditDialogClose"
           :visible.sync="operatorEvidence"
           style="font-size: 0px;">
           <div class="tou">经办人-证明附件</div>
           <div class="line"></div>
           <el-form
             label-position="right"
             label-width="80px"
             :model="formUserList">

               <el-row :span="24">
                 <el-col :span="12" v-show= false>
                   <el-form-item  label-width=120px label="证明文件名">
                   <el-input v-model="formOperatorList.operatorEvidenceContractFileName" auto-complete="off" :disabled=disable ></el-input>
                 </el-form-item>
                 </el-col>
                 <el-col :span="12" v-show= true>
                   <el-form-item  label-width=120px label="证明文件" prop="operatorEvidenceContractFileName">
                   <el-upload
                       class="avatar-uploader"
                       style="width: 100%"
                       action="#"
                       :show-file-list="false"
                       :http-request="httpRequestPre">
                         <el-input label-width=120px v-model="formOperatorList.operatorEvidenceContractFileName" auto-complete="off"  style="width: 100%"></el-input>
                         <!-- <el-button type="primary" @click="getFile(index)">选取文件</el-button> -->
                     </el-upload>
                     <el-input label-width=120px v-model="formOperatorList.operatorEvidenceBase64Str" v-show="false" auto-complete="off"></el-input>
                 </el-form-item>
                 </el-col>
             </el-row>
           </el-form>
           <div slot="footer" class="dialog-footer">
             <el-button @click="operatorEvidenceAdd" type="primary">证明文件上传</el-button>
           </div>
         </el-dialog>
  </div>
</template>

<script type="text/javascript">
import axios from 'axios'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default{
  data() {
    return {
      loading: true,
      rules: {
        companyName: [
          { required: true, message: `请输入企业名称`, trigger: `blur` }
        ],
       operatorName: [
          { required: true, message: `请输入经办人姓名`, trigger: `blur` },
          { min: 2, max: 15, message: `长度在 2 到 15 个字符`, trigger: `blur` }
        ],
        operatorMobile: [
          { required: true, message: `请输入经办人手机号`, trigger: `blur` },
          { min: 11, max: 11, message: `长度在 11 个字符`, trigger: `blur` }
        ],
        contractFileName: [
          { required: true, message: `请输入协议文件`, trigger: `blur` }
        ]

      },
       ruleEmails: {
              companyName: [
                { required: true, message: `请输入企业名称`, trigger: `blur` }
              ],
              invoiceMail: [
                { required: true, message: `请输入公司邮箱`, trigger: `blur` }
              ]

            },
      companyName: ``,
      operatorName: ``,
      comPanyNumList: [],
      customerCompanytable: [],
      hightt: `0px`,
      formOperatorList: {
        'custId': ``,
        'companyName': ``,
        'companyNum': ``,
        'operatorName': ``,
        'operatorMobile': ``,
        'identificationId': ``,
        'contractFileName': ``,
        'base64Str': ``
      },
       formEditEmailList: {
              'companyName': ``,
              'companyNum': ``,
              'customerName': ``,
              'invoiceMail': ``
            },
      current: 1,
      pagesize: 8,
      // 总共有多少条数据
      total: 0,
      addOperatorList: false,
      addEditEmailList: false,
      operatorEvidence: false
    }
  },
  created() {
    this.heightt = tableHeight // eslint-disable-line
    this.loadCompanyNumList()
    this.loadData()
  },
  methods: {
    // 获取有效的企业编号列表
    async loadCompanyNumList() {
      const response = await this.$http.post(`customer/customeRecQueryList`)
      if (response.data.code == 0) {
        this.comPanyNumList = response.data.data
      }
    },
      httpRequestPre(data) {
                  const isPFX = data.file.type == 'application/pdf';
                  const isLt2M = data.file.size / 1024 / 1024 < 10;

                  if (!isPFX) {
                    this.$message.error('上传文件只能是pdf格式!');
                  }else if (!isLt2M) {
                    this.$message.error('上传文件大小不能超过 10MB!');
                  } else {
                    // 转base64
                    this.getBase64Pre(data.file).then((resBase64) => {
                    this.fileBase64 = resBase64.split(',')[1]//直接拿到base64信息
                     this.formOperatorList.operatorEvidenceBase64Str = resBase64.split(',')[1];
                    })
                    this.$message.success('文件上传成功');
                 }
              },
          getBase64Pre(file) {
                        this.formOperatorList.operatorEvidenceContractFileName = file.name;
                        this.$forceUpdate()
                        return new Promise((resolve, reject) => {
                          let reader = new FileReader();
                          let fileResult = '';
                          reader.readAsDataURL(file);
                          reader.onload = function() {
                            fileResult = reader.result;
                          };
                          reader.onerror = function(error) {
                            reject(error);
                          };
                          reader.onloadend = function() {
                            resolve(fileResult);
                          };
                        });
                  },
     async operatorEvidenceAdd(){
                const response = await this.$http.post(`customerCompany/operatorEvidenceAdd`, this.formOperatorList);
                     if(response.data.code == 0) {
                       this.loadData();
                       this.$message({
                         type: 'success',
                         message: '证明文件上传成功'
                       });
                     }else {
                       this.$message({
                         type: 'error',
                         message: '证明文件上传失败：'+response.data.msg
                       });
                     }
             },

httpRequest(data) {
        const isPFX = data.file.type == 'application/pdf';
        const isLt2M = data.file.size / 1024 / 1024 < 10;

        if (!isPFX) {
          this.$message.error('上传文件只能是pdf格式!');
        }else if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 10MB!');
        } else {
          // 转base64
          this.getBase64(data.file).then((resBase64) => {
          this.fileBase64 = resBase64.split(',')[1]//直接拿到base64信息
           this.formOperatorList.base64Str = resBase64.split(',')[1];
          })
          this.$message.success('文件上传成功');
       }
    },
      getBase64(file) {
                  this.formOperatorList.contractFileName = file.name;
                  this.$forceUpdate()
                  return new Promise((resolve, reject) => {
                    let reader = new FileReader();
                    let fileResult = '';
                    reader.readAsDataURL(file);
                    reader.onload = function() {
                      fileResult = reader.result;
                    };
                    reader.onerror = function(error) {
                      reject(error);
                    };
                    reader.onloadend = function() {
                      resolve(fileResult);
                    };
                  });
            },
  changeRow() {
    //debugger
    // 根据选择的企业名称查找对应的对象，并获取企业编码值
    const selectedOption = this.comPanyNumList.find(function(item) {
      return item.companyName === this.formOperatorList.companyName;
    }.bind(this));
    if (selectedOption) {
      this.formOperatorList.companyNum = selectedOption.companyNum;
      this.formOperatorList.custId = selectedOption.customerName;
      // console.log(this.formOperatorList)
    } else {
      this.formOperatorList.companyNum = '';
    }
  },
  changeRowEditEmail() {
         // 根据选择的企业名称查找对应的对象，并获取企业编码值
          const selectedOption = this.comPanyNumList.find(function(item) {
            return item.companyName === this.formEditEmailList.companyName;
          }.bind(this));
          if (selectedOption) {
            this.formEditEmailList.companyNum = selectedOption.companyNum;
            this.formEditEmailList.customerName = selectedOption.customerName;
          } else {
            this.formEditEmailList.companyNum = '';
          }
    },
    firstLoadData() {
      this.current = 1
      this.pagesize = 8
      this.queryLook()
    },
    // 列表展示
    async loadData() {
      const formData = new FormData()
      formData.append(`current`, this.current)
      formData.append(`size`, this.pagesize)
      const response = await this.$http.post(`customerCompany/page`, formData)
      if (response.data.code == 0) {
        this.loading = false
        this.customerCompanytable = response.data.data.records
        this.total = response.data.data.total
      }
    },
    // 查询
    async queryLook() {
      const formData = new FormData()
      formData.append(`current`, this.current)
      formData.append(`size`, this.pagesize)
      formData.append(`companyName`, this.companyName)
      formData.append(`operatorName`, this.operatorName)
      const response = await this.$http.post(`customerCompany/page`, formData)
      if (response.data.code == 0) {
        this.loading = false
        this.customerCompanytable = response.data.data.records
        this.total = response.data.data.total
      }
    },
    // 新增用户
    addData(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
            const loading = this.$loading({
             lock: true,
             text: '保存中，请稍后...',
             spinner: 'el-icon-loading',
             background: 'rgba(0, 0, 0, 0.7)'
           });
          const response = await this.$http.post(`customerCompany/detailAdd`, this.formOperatorList)
          if (response.data.code == 0) {
            this.loadData()
            this.addOperatorList = false
            loading.close();
            this.$message({
              type: `success`,
              message: `添加成功`
            })
          } else {
          loading.close();
            this.$message({
              type: `error`,
              message: response.data.msg
            })
          }
        } else {
          this.$message.error(`请查看是否有选项未填写或填错项`)
          return false
        }
      })
    },

     // 修改邮箱
        editEmail(formName) {
          this.$refs[formName].validate(async(valid) => {
            if (valid) {
                const loading = this.$loading({
                 lock: true,
                 text: '保存中，请稍后...',
                 spinner: 'el-icon-loading',
                 background: 'rgba(0, 0, 0, 0.7)'
               });
              const response = await this.$http.post(`customer/customerRecEditMail`, this.formEditEmailList)
              if (response.data.code == 0) {
                this.loadData()
                this.addEditEmailList = false
                loading.close();
                this.$message({
                  type: `success`,
                  message: `更新成功`
                })
              } else {
              loading.close();
                this.$message({
                  type: `error`,
                  message: response.data.msg
                })
              }
            } else {
              this.$message.error(`请查看是否有选项未填写或填错项`)
              return false
            }
          })
        },
    // 证明材料
    async openChange(recoder) {
      this.operatorEvidence = true;
     const response = await this.$http.post(`customerCompany/noCarCompanyMangerQuery`, {'companyNum': recoder.companyNum, 'contractFileName': recoder.contractFileName});
       if (response.data.code == 0) {
         this.formOperatorList = response.data.data;
        // this.disable = !((this.formOperatorList.interType == 1) && (this.formOperatorList.recStatus == 2));
       }
    },
    // 清空表单数据
    handleEditDialogClose() {
      for (var key in this.formOperatorList) {
        this.formOperatorList[key] = ``
      };

      for (var key1 in this.formEditEmailList) {
              this.formEditEmailList[key1] = ``
       };

      this.operatorEvidence = false;
      this.current = 1
      this.pagesize = 8
    },
    // 分页方法
    handleSizeChange(val) {
      this.pagesize = val
      if (this.companyName != `` || this.operatorName != ``) {
        this.queryLook()
      } else {
        this.loadData()
      };
    },
    handleCurrentChange(val) {
      this.current = val
      if (this.companyName != `` || this.operatorName != ``) {
        this.queryLook()
      } else {
        this.loadData()
      };
    },
    // 导出表格所用
    async exportExcel() {
      const loading = this.$loading({
        lock: true,
        text: `系统正在努力接收中，过程大概需要几分钟的时间，请您耐心等待...`,
        spinner: `el-icon-loading`,
        background: `rgba(0, 0, 0, 0.7)`
      })
      let curr = this.current
      let pagesize1 = this.pagesize
      this.current = 1
      this.pagesize = this.total
      await this.loadData()
      // 设置当前日期
      let time = new Date()
      let year = time.getFullYear()
      let month = time.getMonth() + 1
      let day = time.getDate()
      let name = `企业经办人信息列表_` + year + `` + month + `` + day
      /* generate workbook object from table */
      //  .table要导出的是哪一个表格
      var wb = XLSX.utils.table_to_book(document.querySelector(`.table`), { raw: true })
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: `xlsx`,
        bookSST: true,
        type: `array`
      })
      try {
        //  name+'.xlsx'表示导出的excel表格名字
        FileSaver.saveAs(
          new Blob([wbout], { type: `application/octet-stream` }),
          name + `.xlsx`
        )
      } catch (e) {
      }
      this.current = curr
      this.pagesize = pagesize1
      this.loadData()
      loading.close()
      return wbout
    }

  }
}
</script>

<style>
.system-user {
  border: 1px solid #d9d9d9;
  border-radius: 10px;
}
.system-user .title {
  font-size: 5px;
  margin-bottom: 20px;
}
.system-user .top {
  padding-top: 20px;
  padding-left: 20px;
}
.system-user .text {
  display: inline-block;
  color: #000;
  font-size: 16px ;
  margin-left: 1%;
}
.system-user .input-demo {
  display: inline-block;
  width: 20%;
  margin-left: 1%;
}
.system-user .block {
  font-size: 5px;
  text-align: center;
  margin-top: 25px;
  margin-bottom: 25px;
}
.system-user .el-dialog {
  width: 60%;
}
.system-user .el-dialog__header, .el-dialog__body {
  padding: 0 20px;
}
.system-user .tou {
  font-size: 20px;
  height: 30px;
  line-height: 30px;
  padding-top: 15px;
}
.system-user .line {
  margin-top: 15px;
  margin-bottom: 15px;
  width: 100%;
  height: 2px;
  background-color: #d9d9d9;
}
.system-user .xinxi {
  text-align: center;
  margin: 15px auto;
  font-size: 18px;
}
</style>
