<!-- 主页模块 主页一览-->
<template>
  <el-tabs v-model="activeName"
           v-loading.fullscreen.lock="fullscreenLoading">
    <el-tab-pane label="租户管理"
                 name="first">
      <div>
        <div class="top-buttons">
          <el-button type="primary"
                     size="small"
                     @click="add">新增</el-button>
          <div class="search">
            <el-input v-model="page.keyword"
                      placeholder="请输入搜索内容"
                      size="small"
                      class="page-search"
                      clearable
                      @clear="getList"
                      @keyup.enter.native="getList">111</el-input>
            <svg-icon icon-class="gen"
                      class="genIcon"
                      @click="getList" />
          </div>
        </div>
        <div class="table">
          <el-table :data="tableData"
                    style="width: 100%"
                    @cell-mouse-enter="mouseEnter"
                    @row-click="handleRowClick">
            <!-- <el-table-column type="selection" width="30" align="center" /> -->
            <el-table-column prop="roleId"
                             label="序号"
                             width="50"
                             align="center">
              <template slot-scope="scope">{{ scope.$index + 1 }}</template>
            </el-table-column>
            <el-table-column prop="tenantName"
                             label="公司名称" />
            <el-table-column prop="linkmanName"
                             label="联系人" />
            <!-- <el-table-column prop="address" label="开通服务数" /> -->
            <el-table-column prop="contractStartDate"
                             label="入驻时间" />
            <el-table-column prop="contractEndDate"
                             label="到期日期" />
            <el-table-column prop="action"
                             label="操作"
                             width="100"
                             align="center">
              <template slot-scope="scope">
                <yh-operaction :lable="getLableList(scope.row)"
                               @skip="skp" />
              </template>

            </el-table-column>
          </el-table>
          <pagination v-show="total > 0"
                      :total="total"
                      :page.sync="page.currentPage"
                      :limit.sync="page.pageSize"
                      @pagination="getList" />
        </div>
        <!-- 批量导入船员 -->
        <el-dialog v-loading="loadingEnter"
                   title="批量导入船员"
                   :visible.sync="importTF"
                   width="650px"
                   :before-close="handleClose"
                   :close-on-click-modal="false">
          <span>
            <el-upload ref="import"
                       class="upload-demo"
                       :auto-upload="false"
                       action
                       :file-list="enterList"
                       :limit="2"
                       :on-change="handleChange"
                       :on-remove="removeFile">
              <el-button slot="trigger"
                         class="uploadBtn"
                         size="small"
                         type="primary">选择文件</el-button>
              <div slot="tip"
                   class="el-upload__tip excelUpload">
                只能上传“船员批量导入模板”
              </div>
            </el-upload>
            <a class="downLoad"
               :href="downloadUrl">下载船员批量导入空白模板</a>
          </span>
          <span slot="footer"
                class="dialog-footer">
            <el-button @click="clear">取 消</el-button>
            <el-button type="primary"
                       @click="enterOk">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog v-loading="loadingEnter"
                   title="重复性校验"
                   class="repeatDialog"
                   :visible.sync="repeatsTF"
                   width="700px"
                   :before-close="cancel"
                   :close-on-click-modal="false">
          <span>
            <p class="msgTitle"
               v-if="allRowMsg.noRepeats !== null">
              {{
                repeatsMsg.seafarerCorrectInfos[0] + ',' + repeatsMsg.seafarerCorrectInfos[1] + ',' + repeatsMsg.seafarerCorrectInfos[2]
              }}
            </p>
            <p class="msgTitle"
               v-else>
              未找到重复的船员信息
            </p>
            <div v-show="allRowMsg.noRepeats !== null">
              <p class="tab-title">
                {{ Amount }}/{{ length1 }}
                身份证号或手机号重复的船员信息如下 :
              </p>
              <el-table ref="multipleTable"
                        :data="tableData1"
                        class="repeatTable"
                        tooltip-effect="dark"
                        style="width: 100%"
                        @selection-change="val => handleSelectionChange(val)">
                <el-table-column type="selection"
                                 width="55">
                </el-table-column>
                <el-table-column label="本次导入的船员">
                  <template slot-scope="scope">
                    <div class="importCrew">
                      <p>姓名: {{scope.row.excelSeafarer.seafarerName}}</p>
                      <p>身份证号: {{scope.row.excelSeafarer.seafarerIdNo}}</p>
                      <p>联系电话: {{scope.row.excelSeafarer.mobilePhone}}</p>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="已在船员库的船员">
                  <template slot-scope="scope">
                    <div class="hasBeenCrew">
                      <p>姓名: {{scope.row.dataSeafarer.seafarerName}}</p>
                      <p>身份证号: {{scope.row.dataSeafarer.seafarerIdNo}}</p>
                      <p>联系电话: {{scope.row.dataSeafarer.mobilePhone}}</p>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <div>
                <!-- <el-checkbox v-model="checked">后续船员都执行此操作</el-checkbox> -->
                <div class="btn"
                     align="right">
                  <el-button @click="cancelPhone">取 消</el-button>
                  <el-button type="primary"
                             @click="coverPhone">覆 盖</el-button>
                </div>
              </div>
            </div>
          </span>
          <!-- <span slot="footer"
                class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
          </span> -->
        </el-dialog>
      </div>
    </el-tab-pane>
    <el-tab-pane label="试用租户"
                 name="tryUser">
      <div class="top-buttons">
        <div class="nav-search">
          <!-- 租户状态 -->
          <div class="searchTwo">
            <ws-dropdown trigger="click"
                         class="dropdown"
                         @command="tenantStatus">
              <span class="el-dropdown-link">
                {{ tenantStatusName }}
                <i class="iconfont icondropDown"></i>
              </span>
              <ws-dropdown-menu slot="dropdown"
                                style="max-width:200px;overflow-x: auto">
                <ws-dropdown-item v-for="item in statusList"
                                  :key="item.statusFlag"
                                  :command="item.statusFlag"
                                  style="word-break: break-all;white-space: nowrap;">
                  {{ item.valueEn }}
                </ws-dropdown-item>
              </ws-dropdown-menu>
            </ws-dropdown>
          </div>
          <div class="search"
               style="float:left">
            <el-input v-model="trialpage.keyword"
                      placeholder="请输入公司名称、联系人"
                      size="small"
                      class="page-search"
                      clearable
                      @clear="getTrial"
                      @keyup.enter.native="getTrial">111</el-input>
            <svg-icon icon-class="gen"
                      class="genIcon"
                      @click="getTrial" />
          </div>
        </div>
      </div>
      <div class="table">
        <el-table :data="tableTrialData"
                  style="width: 100%"
                  @cell-mouse-enter="mouseEnter"
                  @row-click="handleTrialClick">
          <el-table-column prop="roleId"
                           label="序号"
                           width="50"
                           align="center">
            <template slot-scope="scope">{{
              (trialpage.currentPage - 1) * 10 + scope.$index + 1
            }}</template>
          </el-table-column>
          <!-- 联系人 -->
          <el-table-column width="100"
                           prop="linkmanName"
                           label="联系人">
            <template slot-scope="{ row }">
              {{ row.linkmanName | empty}}
            </template>
          </el-table-column>
          <!-- 联系电话 -->
          <el-table-column prop="linkmanPhone"
                           label="联系电话">
            <template slot-scope="{ row }">
              {{ row.linkmanPhone }}
            </template>
          </el-table-column>
          <!-- 公司名称 -->
          <el-table-column prop="tenantName"
                           label="公司名称">
            <template slot-scope="{ row }">
              {{ row.tenantName | empty}}
            </template>
          </el-table-column>
          <!-- 创建时间 -->
          <el-table-column prop="createDate"
                           width="140"
                           label="创建时间">
            <template slot-scope="{ row }">
              {{ row.createDate  | empty}}
            </template>
          </el-table-column>
          <!-- 负责人 -->
          <el-table-column prop="customerServiceStaffName"
                           label="负责人">
            <template slot-scope="{ row }">
              {{ row.customerServiceStaffName  | empty}}
            </template>
          </el-table-column>
          <!-- 跟踪状态 -->
          <el-table-column prop="status"
                           width="80"
                           label="跟踪状态">
            <template slot-scope="{ row }">
              {{ row.status | empty}}
            </template>
          </el-table-column>
          <!-- 试用期限 -->
          <el-table-column prop="action"
                           width="170"
                           label="试用期限">
            <template slot-scope="{ row }">
              <span v-if="row.contractStartDate !== null || row.contractEndDate !== null ">{{ row.contractStartDate }}~{{ row.contractEndDate }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <!-- 剩余天数 -->
          <el-table-column prop="daysRemaining"
                           width="100"
                           label="剩余天数">
            <template slot-scope="{ row }">
              <span v-if="row.statusFlag === '2' ">{{ row.daysRemaining }}</span>
              <span v-else>--</span>
            </template>

          </el-table-column>
          <!-- 开通模块 -->
          <!-- <el-table-column prop="openingmodule"
                           label="开通模块">
            <template slot-scope="{ row }">
              {{ row.openingmodule | empty}}
            </template>
          </el-table-column> -->
          <!-- 来源 -->
          <el-table-column prop="tenantSource"
                           label="来源">
            <template slot-scope="{ row }">
              {{ row.tenantSource | empty}}
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="totalTrial > 0"
                    :total="totalTrial"
                    :page.sync="trialpage.currentPage"
                    :limit.sync="trialpage.pageSize"
                    @pagination="getTrial" />
      </div>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
import {
  tenants,
  enable,
  disable,
  importFile,
  tenantDetail,
  coverSeafarers,
  createSeafarers,
  saveAccountData, // 备份账号数据
  recoveryAccountData, // 还原账号数据
  getTrialList //获取试用租户列表
} from "../../api/lessee";
import Pagination from "../../components/Pagination";
import yhOperaction from "../../layout/components/common/operaction.vue";
export default {
  name: "Lessee",
  components: {
    yhOperaction,
    Pagination
  },
  // 空内容填充‘--’字符
  filters: {
    empty (value) {
      let empt = "";
      if (!value) {
        empt = "--";
      } else {
        empt = value;
      }
      return empt;
    },
  },
  data () {
    return {
      Amount: 0,
      fullscreenLoading: false,
      // 船员状态
      statusList: [
        {
          statusFlag: "",
          valueEn: "全部"
        },
        {
          statusFlag: "1",
          valueEn: "待核实"
        },
        {
          statusFlag: "2",
          valueEn: "试用中"
        },
        {
          statusFlag: "3",
          valueEn: "使用中"
        },
        {
          statusFlag: "4",
          valueEn: "停用"
        }
      ],
      tenantStatusName: "全部",
      tableTrialData: [], //试用租户的table
      activeName: "first", //进入页面 默认显示哪个tabs
      trialpage: {
        currentPage: 1,
        pageSize: 10,
        keyword: "",
        statusFlag: ""
      },
      rowMsg: "",
      page: {
        currentPage: 1,
        pageSize: 10,
        keyword: ""
      },
      total: 0,
      totalTrial: 0,
      sousuo: "",
      lable: [
        {
          lab: "编辑",
          click: "edit",
          isShow: true
        },
        {},
        {
          lab: "批量导入",
          click: "import",
          isShow: true
        },
        {
          lab: "备份",
          click: "backup",
          isShow: false
        },
        {
          lab: "还原",
          click: "reduction",
          isShow: false
        }
      ],
      tenantName: {},
      loadingEnter: false,
      enterMsg: {},
      tableData: [],
      importTF: false, // 批量导入
      enterList: [],
      // downloadUrl:
      //   "http://winsea-saas-test.oss-cn-shanghai.aliyuncs.com/saas/template/crew/%E8%88%B9%E5%91%98%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx",
      downloadUrl: process.env.VUE_APP_BASE_API + "/saas/template/crew/船员批量导入导出模板.xlsx",
      repeatsTF: false, // 批量导入重复数据
      repeatsMsg: {
        seafarerCorrectInfos: ["", ""]
      }, // 重复数据
      tableData1: [],
      checked: false,
      allRowMsg: {
        noRepeats: null
      },
      length1: 0,
      length2: 0,
      phoneNum: 0, // 身份证，手机号覆盖计数
      nameNum: 0 // 姓名覆盖计数
    };
  },
  computed: {
    getLableList () {
      return (item) => {
        return this.lable.filter(lableItem => ((!!item.testFlag && !lableItem.isShow) || lableItem.isShow))
      }
    }
  },
  mounted () {
    this.activeName = this.$route.params.type || 'first'
    this.getList();
    this.getTrial();
  },
  methods: {
    //新增试用租户start
    // 租户状态
    tenantStatus (command) {
      let [selectState] = this.statusList
        .filter(item => item.statusFlag === command)
        .map(item => {
          return item.valueEn;
        });
      this.tenantStatusName = selectState;
      this.trialpage.statusFlag = command
      this.getTrial();
    },
    getTrial () {
      getTrialList(this.trialpage).then(res => {
        this.totalTrial = res.data.total
        this.tableTrialData = res.data.records;
      });
    },
    // 跳转到详情页
    handleTrialClick (item) {
      this.$router.push({
        name: "trialDetail",
        query: {
          id: item.tenantId
        }
      });
    },
    // 查询租户详细信息
    checkMsg () {
      tenantDetail({
        tenantId: this.rowMsg.tenantId
      }).then(response => {
        this.tenantName = response.data;
      });
    },
    skp (msg) {
      if (msg === "edit") {
        localStorage.setItem("row", JSON.stringify(this.rowMsg));
        this.$router.push({
          name: "lesseeEdit",
          params: {
            state: false
          }
        });
      } else if (msg === "disable") {
        this.$confirm("此操作将禁用该租户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            disable({
              tenantId: this.rowMsg.tenantId
            }).then(() => {
              this.getList();
              this.$message({
                message: "禁用成功",
                type: "success",
                showClose: true
              });
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消禁用",
              showClose: true
            });
          });
      } else if (msg === "enable") {
        enable({
          tenantId: this.rowMsg.tenantId
        }).then(() => {
          this.getList();
          this.$message({
            message: "启用成功",
            type: "success",
            showClose: true
          });
        });
      } else if (msg === "import") {
        this.checkMsg();
        this.importTF = true;
      } else if (msg === "backup") {
        this.saveAccountDataList()
      } else if (msg === "reduction") {
        this.recoveryAccountDataList()
      }
    },
    saveAccountDataList () {
      this.fullscreenLoading = true;
      saveAccountData()
        .then(res => {
          if (res.code === '200') {
            this.fullscreenLoading = false;
            this.$message({
              message: "备份成功",
              type: "success"
            });
          }

        })
        .catch(error => {
          this.fullscreenLoading = false;
          this.$message({
            type: "error",
            message: "备份失败"
          });
        });
    },
    recoveryAccountDataList () {
      this.fullscreenLoading = true;
      recoveryAccountData()
        .then(res => {
          if (res.code === '200') {
            this.fullscreenLoading = false;
            this.$message({
              message: "还原成功",
              type: "success"
            });
          }

        })
        .catch(error => {
          this.fullscreenLoading = false;
          this.$message({
            type: "error",
            message: "还原失败"
          });
        });
    },
    mouseEnter (row) {
      this.rowMsg = row;
      localStorage.setItem("tenantId", row.tenantId);
      if (row.enabled === 1) {
        this.lable.splice(1, 1, {
          lab: "禁用",
          click: "disable",
          isShow: true
        });
      } else if (row.enabled === 0) {
        this.lable.splice(1, 1, {
          lab: "启用",
          click: "enable",
          isShow: true
        });
      }
    },
    handleRowClick (row, column) {
      if (column.property !== "action") {
        localStorage.setItem("row", JSON.stringify(row));
        this.$router.push({
          name: "lesseeMsg"
        });
      }
    },
    // 查询租户
    getList () {
      tenants(this.page).then(response => {
        this.total = response.data.total;
        this.tableData = response.data.records;
      });
    },
    add () {
      localStorage.setItem("tenantId", "");
      this.$router.push({
        name: "lesseeAdd"
      });
    },
    // 弹出框确认关闭
    handleClose (done) {
      this.clear();
      done();
    },
    handleChange (file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.enterList.splice(0, 1, file);
    },
    removeFile () {
      this.enterList = [];
    },
    // 清空信息
    clear () {
      this.phoneNum = 0;
      this.importTF = false;
      this.enterList = [];
    },
    //重复船员的dialog复选框
    handleSelectionChange (val) {
      console.log(val, 'val')
      this.multipleSelection = val;
      this.Amount = val.length
    },
    enterOk () {
      // 判断是否为空
      if (this.enterList.length <= 0) {
        this.$message({
          type: "error",
          message: "请选择文件",
          showClose: true
        });
      } else {
        const stateList = this.enterList[0].name.split(".");
        const state = stateList[stateList.length - 1];
        const size = this.enterList[0].size;
        if (state !== "xlsx" && state !== "xls") {
          this.$message({
            type: "error",
            message: "文件格式错误，只能选择“船员批量导入模板”表格文件。",
            showClose: true
          });
          return false;
        } else if (size > 100485760) {
          this.$message({
            type: "error",
            message: "文件不能大于100M",
            showClose: true
          });
          return false;
        } else {
          this.enterMsg = new FormData();
          this.enterMsg.append("file", this.enterList[0].raw);
          this.enterMsg.append("compId", this.tenantName.compId);
          this.loadingEnter = true;
          importFile(this.enterMsg)
            .then(response => {
              this.loadingEnter = false;
              if (response.data == null) {
                if (response.code === "SEAFARER_IMPORT_001") {
                  this.$message({
                    type: "error",
                    message: "系统暂时无法处理，请稍后再试",
                    showClose: true
                  });
                }
                if (response.code === "LABOR_STOCK_ERROR_TEMP") {
                  this.$message({
                    type: "error",
                    message: "模板错误，请先下载空白模板，根据模板内容填写完成后再次上传！",
                    showClose: true
                  });
                }
                return false;
              }
              this.allRowMsg = response.data;
              if (response.data.importCode === "SUCCESS") {
                this.clear();
                let repeatMessage = response.data.seafarerCorrectInfos[0] + ',' + response.data.seafarerCorrectInfos[1] + '!'
                this.$message({
                  type: "success",
                  message: repeatMessage,
                  showClose: true
                });
              } else if (response.data.importCode === "REPEATS") {
                if (this.allRowMsg.noRepeats != null) {
                  for (var i = 0; i < response.data.noRepeats.length; i++) {
                    response.data.noRepeats[i].excelSeafarer.seafarerId =
                      response.data.noRepeats[i].dataSeafarer.seafarerId;
                  }
                  this.repeatsMsg = response.data;
                  this.length1 = this.allRowMsg.noRepeats.length;
                  this.tableData1 = this.repeatsMsg.noRepeats
                }
                this.clear();
                this.repeatsTF = true;
              } else if (response.data.importCode === "DATAERROR") {
                this.$message({
                  type: "warning",
                  message: response.data.seafarerErrorInfos.toString(),
                  showClose: true
                });
              }
            })
            .catch(error => {
              this.loadingEnter = false;
              if (error.code === "SEAFARER_IMPORT_001") {
                this.$message({
                  type: "error",
                  message: "系统暂时无法处理，请稍后再试",
                  showClose: true
                });
              } else if (error.code === "SEAFARER_IMPORT_002") {
                this.$message({
                  type: "error",
                  message: "附件时间格式有问题，请参考yyyy/MM/dd",
                  showClose: true
                });
              } else if (error.code === "ERROR_TEMPLATE") {
                this.$message({
                  type: "error",
                  message:
                    "当前导入表格的表头与系统模板表格的表头不一致，请核对后再进行导入！",
                  showClose: true
                });
              } else if (error.code === "ERROR_OOXML") {
                this.$message({
                  type: "error",
                  message:
                    "当前导入表格与系统模板表格不一致，请核对后再进行导入！",
                  showClose: true
                });
              }
            });
        }
      }
    },
    //覆盖
    coverPhone () {
      if (this.Amount === 0) {
        this.$message({
          type: "error",
          message: "请先选择需要覆盖的船员再点击覆盖，如无需覆盖，请点击取消。"
        });
      } else {
        coverSeafarers(
          this.multipleSelection
        )
          .then(() => {
            this.$message({
              type: "success",
              message: "数据覆盖成功"
            });

            this.tableData1 = [];
            this.repeatsTF = false;
          })
          .catch(() => {
            this.loadingEnter = false;
          });
      }

    },
    // 里面的取消
    cancelPhone () {
      this.$confirm("此操作将取消覆盖, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.allRowMsg.noRepeats = null;
          this.repeatsTF = false;
        })
        .catch(() => { });
    },
    cancel () {
      this.phoneNum = 0;
      this.nameNum = 0;
      this.chicked = false;
      this.repeatsTF = false;
    }
  }
};
</script>

<style scoped lang="scss">
.search {
  float: right;
  position: relative;
  width: 232px;
}
.genIcon {
  font-size: 32px;
  position: absolute;
  top: 10px;
  right: 3px;
}
.genIcon:hover {
  cursor: pointer;
}
.downLoad {
  float: right;
  color: #1d6ced;
}
.excelUpload {
  margin-left: 20px;
  display: inline-block;
}
.uploadBtn {
  display: inline-block;
}

.tab-title {
  margin-bottom: 10px;
}
//新增
.top-buttons {
  .nav-search {
    display: flex;
    float: right;
    .searchTwo {
      margin-right: 10px;
    }
  }
}
.importCrew,
.hasBeenCrew {
  p {
    line-height: 20px;
    text-align: left;
  }
}
/deep/ .el-table .cell {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  max-height: 100px;
  font-size: 12px;
}
.btn {
  margin-top: 10px;
}
.repeatTable /deep/ .el-table__body-wrapper {
  overflow-y: auto;
  height: 300px;
}
.repeatDialog /deep/ .el-dialog__body {
  padding: 10px !important;
}
.msgTitle {
  line-height: 24px;
}
</style>
