<!-- 船端成员 -->
<template>
  <div class="box-body">

    <div class="search-box">
      <div class="button-common">
        <el-button type="primary" @click="addman">添加成员</el-button>
        <el-button @click="del">批量删除成员</el-button>
        <!-- <el-button v-if="flagLook" @click="lookforbidden">查看禁用成员</el-button> -->
        <!-- <el-button v-else @click="lookforbiddens">查看非禁用成员</el-button> -->
      </div>

      <div class="search-common">
        <div class="search-info">
          <span>船舶 </span>
          <el-select v-model="page.vesselId" placeholder="请选择" @change="getList" clearable>
            <el-option v-for="item in vesselsList" :key="item.vesselId" :label="item.vesselName" :value="item.vesselId" />
          </el-select>
        </div>
        <div class="search-info">
          <span>部门 </span>
          <el-select v-model="page.deptId" @change="getList" clearable placeholder="请选择">
            <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </div>
        <div class="search-info">
          <el-input class="search-keyword" v-model.trim="page.staffName" maxlength="50" placeholder="请输入成员中文名" @keyup.enter.native="oilInfoSearch" clearable @clear="getClear" />
          <svg-icon icon-class="searchIcon" class="searchIcon" @click="oilInfoSearch" />
        </div>
      </div>

    </div>

    <el-table stripe :data="shoreBasedMembersList" height="58.5vh" v-loading="loadingList" @selection-change="handleSelectionChange" @cell-mouse-enter="mouseEnter" @cell-click="jumpDetail">
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column prop="roleId" label="序号" width="80" align="center">
        <template slot-scope="scope">
          {{(page.currentPage - 1)*page.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="staffName" label="中文名" />
      <el-table-column prop="majorRole.roleName" label="职务" />
      <el-table-column prop="deptName" label="部门名称" />
      <el-table-column prop="vesselName" label="所属船舶" />
      <el-table-column prop="staffMobilePhone" label="手机号" />
      <el-table-column prop="staffAccount" label="账号ID" />
      <el-table-column prop="unclick" label="操作" width="100" align="center">
        <yh-operaction :lable="lable" @skip="skp" />
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="page.currentPage" :limit.sync="page.pageSize" @pagination="getList" />

    <!-- 查看 -->
    <el-dialog v-loading="loadingSave" :title="deptTitle" :visible.sync="addCompanyFlag" width="880px" center :close-on-click-modal="false" @close="cancel">
      <div class="two-form">
        <el-form :model="addDeptInfo">
          <el-form-item label="中文名：">
            {{addDeptInfo.staffName | empty}}
          </el-form-item>
          <el-form-item label="账号：">
            {{addDeptInfo.staffAccount | empty}}
          </el-form-item>
          <el-form-item label="手机号：">
            {{addDeptInfo.staffMobilePhone | empty}}
          </el-form-item>
          <el-form-item label="所属船舶：">
            {{ addDeptInfo.vesselName | empty }}
          </el-form-item>
          <el-form-item label="职务：">
            {{addDeptInfo.roleNames | empty}}
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog v-loading="loadingSave" :title="deptTitles" :visible.sync="editCompanyFlag" width="880px" center :close-on-click-modal="false" @close="cancels">
      <div class="two-form">
        <el-form ref="editDeptInfo" :rules="addDeptInfoRules" :model="editDeptInfo">
          <el-form-item label="中文名" prop="staffName">
            <el-input maxlength="50" v-model="editDeptInfo.staffName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="账号" prop="staffAccount" class="serviceType">
            <span class="tips">
              <svg-icon icon-class="tips" />
              <p>成员唯一标识，可以使用工号、邮箱等<br>公司系统内统一的ID</p>
            </span>
            <el-input v-model="editDeptInfo.staffAccount" placeholder="登录账号唯一标识" />
          </el-form-item>
          <el-form-item label="密码" prop="loginPassword" v-if="flag">
            <el-input clearable :type="inputType" autocomplete="new-password" name="password" @focus="changeInputType" v-model="editDeptInfo.loginPassword" minlength="6" maxlength="20" placeholder="密码任意6位数字，大小写字母，符号组合" />
          </el-form-item>
          <el-form-item v-else label="密码">
            <el-input clearable :type="inputType" placeholder="******" autocomplete="new-password" name="password" @focus="changeInputType" v-model="editDeptInfo.loginPassword" minlength="6" maxlength="20" />
          </el-form-item>
          <el-form-item label="确认密码" prop="loginPasswordAgain" v-if="flag || (!flag && editDeptInfo.loginPassword && editDeptInfo.loginPassword.length > 0)">
            <el-input clearable :type="inputType" autocomplete="new-password" name="password" @focus="changeInputType" v-model="editDeptInfo.loginPasswordAgain" minlength="6" maxlength="20" placeholder="请再次确认密码" />
          </el-form-item>
          <el-form-item label="确认密码" v-show="!(flag || (!flag && editDeptInfo.loginPassword && editDeptInfo.loginPassword.length > 0))">
            <el-input clearable :type="inputType" placeholder="******" autocomplete="new-password" name="password" @focus="changeInputType" v-model="editDeptInfo.loginPasswordAgain" minlength="6" maxlength="20" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input maxlength="50" v-model="editDeptInfo.staffMobilePhone" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="所属船舶" prop="vesselName">
            <el-select v-model="editDeptInfo.vesselName" placeholder="请选择所属船舶" @change="vesselPage">
              <el-option v-for="item in vesselsList" :key="item.vesselId" :label="item.vesselName" :value="item.vesselId" />
            </el-select>
          </el-form-item>
          <el-form-item label="职务" prop="roleName">
            <el-select v-model="editDeptInfo.roleName" placeholder="请选择" @change="depPage">
              <el-option v-for="item in postList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveAndContinueCreating" v-if="flag">保存并继续创建</el-button>
        <el-button type="primary" @click="saveAdd">保 存</el-button>
        <el-button @click="cancels">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import shoreApi from "../../api/organization/shore";
import Pagination from "../../components/Pagination";
import {
  staffPageByCondition,
  remove,
  create,
  findRoles,
  changeInfo,
  company
} from "../../api/shoreBasedMembers";
import { getVessels } from "../../api/organization/orgAddMan";
import yhOperaction from "../../layout/components/operaction.vue";

export default {
  name: "crewMembers",
  components: {
    yhOperaction,
    Pagination
  },
  data() {
    const staffName = (rule, value, callback) => {
      if (!value) {
        callback(
          this.$message({
            type: "error",
            message: "带*号的为必填项",
            showClose: true
          })
        );
      } else {
        callback();
      }
    };
    const validcodeId = (rule, value, callback) => {
      const reg = /[0-9a-zA-Z]$/;
      if (value === "") {
        callback(
          this.$message({
            type: "error",
            message: "带*号的为必填项",
            showClose: true
          })
        );
      } else if (!reg.test(value)) {
        callback(
          this.$message({
            type: "error",
            message: "账号必须是由数字和字母组合",
            showClose: true
          })
        );
      } else {
        callback();
      }
    };
    const validPasswordAgain = (rule, value, callback) => {
      if (value === "") {
        callback(
          this.$message({
            type: "error",
            message: "带*号的为必填项",
            showClose: true
          })
        );
      } else if (value !== this.editDeptInfo.loginPassword) {
        callback(
          this.$message({
            type: "error",
            message: "两次密码不一致",
            showClose: true
          })
        );
      } else {
        callback();
      }
    };
    const validcodeName = (rule, value, callback) => {
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
      if (value === "") {
        callback(
          this.$message({
            type: "error",
            message: "带*号的为必填项",
            showClose: true
          })
        );
      } else if (!reg.test(value)) {
        callback(
          this.$message({
            type: "error",
            message: "密码必须是由6位数字和字母组合",
            showClose: true
          })
        );
      } else {
        callback();
      }
    };
    const validcodePhonee = (rule, value, callback) => {
      const reg = /^1[34578]\d{9}$/;
      if (value === "") {
        callback(
          this.$message({
            type: "error",
            message: "带*号的为必填项",
            showClose: true
          })
        );
      } else if (!reg.test(value)) {
        callback(
          this.$message({
            type: "error",
            message: "手机号格式填写错误",
            showClose: true
          })
        );
      } else {
        callback();
      }
    };
    return {
      roleNames: "",
      flagLook: true,
      flag: false,
      loadingList: false,
      addDeptInfo: {
        vesselBankFlag: "V",
        deptId: ""
      },
      editDeptInfo: {
        vesselBankFlag: "V",
        loginPasswordAgain: '',
        deptId: "",
        roleName: "",
        roles: [
          {
            roleId: "",
            major: "1"
          }
        ],
        vessels: [
          {
            vesselId: ""
          }
        ]
      },
      addDeptInfoRules: {
        staffAccount: [
          {
            required: true,
            validator: validcodeId,
            trigger: "blur"
          }
        ],
        loginPassword: [
          {
            required: true,
            validator: validcodeName,
            trigger: "blur"
          }
        ],
        staffMobilePhone: [
          {
            required: true,
            validator: validcodePhonee,
            trigger: "blur"
          }
        ],
        deptId: [
          {
            required: true,
            trigger: "change"
          }
        ],
        loginPasswordAgain: [
          {
            required: true,
            validator: validPasswordAgain,
            trigger: "blur"
          }
        ],
        staffName: [{ required: true, trigger: "blur" }],
        vesselName: [{ required: true, trigger: "blur" }],
        // loginPasswordAgain: [{ required: true, trigger: "change" }],
        roleName: [{ required: true, trigger: "change" }]
      },
      page: {
        compId: localStorage.getItem("enterprise-front-companyId"),
        underCompId: "",
        deptId: "",
        enabled: "1",
        deleteFlag: "",
        vesselBankFlag: "V",
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      total: 0,
      rules: {
        staffAccount: [
          {
            required: true,
            validator: validcodeId,
            trigger: "blur"
          }
        ],
        loginPassword: [
          {
            required: true,
            validator: validcodeName,
            trigger: "blur"
          }
        ],
        staffMobilePhone: [
          {
            required: true,
            validator: validcodePhonee,
            trigger: "blur"
          }
        ],
        deptId: [
          {
            required: true,
            trigger: "change"
          }
        ]
      },
      shoreBasedMembersList: [],
      postList: [],
      postListList: {
        compId: localStorage.getItem("enterprise-front-companyId"),
        pageSize: 50,
        currentPage: 1,
        vesselBankFlag: "V"
      },
      vesselsList: [],
      vesselList: [],
      deptList: [],
      companyList: [],
      deptTitle: "",
      deptTitles: "",
      addCompanyFlag: false,
      editCompanyFlag: false,
      loadingSave: false,
      msgRow: "",
      name: "",
      names: [],
      tabellist: {
        staffIds: []
      },
      roleName: "",
      vesselName: "",
      inputType: "text"
    };
  },
  computed: {
    lable() {
      return [
        {
          lab: "编辑",
          click: "edit"
        },
        {
          lab: "删除",
          click: "delete"
        }
      ];
    }
  },
  created() {
    this.getList();
  },
  methods: {
    jumpDetail(row, column) {
      if (column.property !== "unclick") {
        this.addDeptInfo = JSON.parse(JSON.stringify(row));
        this.deptTitle = "查看成员";
        if (row.majorRole !== null) {
          this.addDeptInfo.roleNames = row.majorRole.roleName;
        }
        this.addCompanyFlag = true;
      }
    },
    getZhiwu() {
      company(this.postListList).then(response => {
        this.postList = response.records;
      });
      getVessels().then(response => {
        this.vesselsList = response;
      });
    },
    changeInputType() {
      this.inputType = "password";
    },
    getList() {
      this.getShoreDeptList();
      staffPageByCondition(this.page)
        .then(response => {
          this.total = response.total;
          this.shoreBasedMembersList = response.records;
          this.vesselList = response.records.vessels;
          this.loadingSave = false;
        })
        .catch(() => {});
      this.getZhiwu();
    },

    // 批量删除
    del() {
      if (this.tabellist.staffIds.length === 0) {
        this.$message({
          message: "请选择要删除的成员",
          type: "error",
          showClose: true
        });
        return false;
      }
      this.$confirm("删除后，" + this.names + "的账号数据也被清空", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          remove(this.tabellist)
            .then(() => {
              this.$message({
                message: "删除成功",
                type: "success",
                showClose: true
              });
              this.getList();
            })
            .catch(() => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
            showClose: true
          });
        });
    },
    mouseEnter(row, column) {
      this.msgRow = row;
    },
    /* 查看禁用船员 */
    lookforbidden() {
      this.flagLook = false;
      this.page.enabled = "0";
      this.getList();
    },
    lookforbiddens() {
      this.flagLook = true;
      this.page.enabled = "1";
      this.getList();
    },
    handleSelectionChange(val) {
      this.tabellist.staffIds = [];
      this.names = [];
      for (let i = 0; i < val.length; i++) {
        this.tabellist.staffIds.push(val[i].staffId);
        this.names.push(val[i].staffName);
      }
    },
    // 操作下拉
    skp(data) {
      if (data === "see") {
        this.getSee(this.msgRow);
      } else if (data === "edit") {
        this.getEdit(this.msgRow);
      } else if (data === "delete") {
        this.getDelete(this.msgRow);
      }
    },
    // 编辑
    getEdit(row) {
      this.editDeptInfo = JSON.parse(JSON.stringify(row));
      if (row.majorRole !== null) {
        this.editDeptInfo.roleId = row.majorRole.roleId;
      }

      if (row.majorRole !== null) {
        // this.editDeptInfo.roleName = row.majorRole.roleId;
        this.$set(this.editDeptInfo, "roleName", row.majorRole.roleName);
      }

      this.deptTitles = "编辑成员";
      this.editCompanyFlag = true;
    },
    // 删除
    getDelete(row) {
      this.name = row.staffName;
      this.tabellist.staffIds[0] = row.staffId;
      this.$confirm("删除后，" + this.name + "的账号数据也被清空", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          remove(this.tabellist)
            .then(response => {
              this.$message({
                type: "success",
                message: "删除成功"
              });
              this.getList();
            })
            .catch(err => {
              if (err === "MANAGEMENT_008") {
                this.$message({
                  message: "当前部门不允许被删除!",
                  type: "warning"
                });
              }
            });
        })
        .catch(() => {});
    },
    vesselPage(key) {
      const arr = this.vesselsList;
      let that = this;
      arr.forEach(function(item) {
        if (key === item.vesselId) {
          that.editDeptInfo.vesselName = item.vesselName;
          that.editDeptInfo.vesselId = item.vesselId;
        }
      });
    },
    depPage(key) {
      const arr = this.postList;
      let that = this;

      arr.forEach(function(item) {
        if (key === item.roleId) {
          that.editDeptInfo.roleName = item.roleName;
          that.editDeptInfo.roleId = item.roleId;
          that.editDeptInfo.deptName = item.deptName;
          that.editDeptInfo.deptId = item.deptId;
        }
      });
    },
    // 保存后继续创建
    saveAndContinueCreating() {
      this.$refs.editDeptInfo.validate(valid => {
        if (valid) {
          this.loadingSave = true;
          let aaa = [
            {
              roleId: "",
              roleName: "",
              major: "1"
            }
          ];
          let bbb = [
            {
              vesselId: "",
              vesselName: ""
            }
          ];
          aaa = aaa.map(item => {
            return {
              ...item,
              roleId: this.editDeptInfo.roleId,
              roleName: this.editDeptInfo.roleName,
              deptName: this.editDeptInfo.deptName,
              deptId: this.editDeptInfo.deptId
            };
          });
          bbb = bbb.map(item => {
            return {
              ...item,
              vesselId: this.editDeptInfo.vesselId,
              vesselName: this.editDeptInfo.vesselName
            };
          });
          this.editDeptInfo.majorRoleId = this.editDeptInfo.roleId;
          this.editDeptInfo.roles = aaa;
          this.editDeptInfo.vessels = bbb;
          create(this.editDeptInfo)
            .then(response => {
              this.$message({
                message: "保存成功",
                type: "success"
              });
              this.editDeptInfo = {
                /* 部门id */
                staffName: "",
                staffNameEn: "",
                staffAccount: "",
                loginPassword: "",
                staffMobilePhone: "",
                userHeadimg: "",
                roles: [
                  {
                    roleId: "",
                    major: "1"
                  }
                ],
                vessels: [
                  {
                    vesselId: ""
                  }
                ]
              };
              this.loadingSave = false;
              this.getList();
            })
            .catch(err => {
              if (err === "MANAGEMENT_001") {
                this.$message({
                  message: "当前用户名冲突!",
                  type: "warning"
                });
              }
              if (err === "MANAGEMENT_002") {
                this.$message({
                  message: "手机号冲突!",
                  type: "warning"
                });
              }
              if (err === "MANAGEMENT_003") {
                this.$message({
                  message: "邮箱冲突!",
                  type: "warning"
                });
              }
              this.editDeptInfo = {
                /* 部门id */
                staffName: "",
                staffNameEn: "",
                staffAccount: "",
                loginPassword: "",
                staffMobilePhone: "",
                userHeadimg: "",
                roles: [
                  {
                    roleId: "",
                    major: "1"
                  }
                ],
                vessels: [
                  {
                    vesselId: ""
                  }
                ]
              };
              this.loadingSave = false;
            });
        } else {
          this.$message({
            message: "带*号的为必填项！",
            type: "error"
          });
          return false;
        }
      });
    },
    saveAdd() {
      this.$refs.editDeptInfo.validate(valid => {
        if (valid) {
          this.loadingSave = true;
          let aaa = [
            {
              roleId: "",
              roleName: "",
              major: "1"
            }
          ];
          let bbb = [
            {
              vesselId: "",
              vesselName: ""
            }
          ];
          aaa = aaa.map(item => {
            return {
              ...item,
              roleId: this.editDeptInfo.roleId,
              roleName: this.editDeptInfo.roleName,
              deptName: this.editDeptInfo.deptName,
              deptId: this.editDeptInfo.deptId
            };
          });
          bbb = bbb.map(item => {
            return {
              ...item,
              vesselId: this.editDeptInfo.vesselId,
              vesselName: this.editDeptInfo.vesselName
            };
          });
          this.editDeptInfo.majorRoleId = this.editDeptInfo.roleId;
          this.editDeptInfo.roles = aaa;
          this.editDeptInfo.vessels = bbb;
          if (this.editDeptInfo.staffId) {
            changeInfo(this.editDeptInfo)
              .then(response => {
                this.cancels();
                this.$message({
                  message: "修改成功",
                  type: "success"
                });
                this.getList();
              })
              .catch(err => {
                if (err === "MANAGEMENT_010") {
                  this.$message({
                    message: "成员名称重复!",
                    type: "warning"
                  });
                }
                this.loadingSave = false;
              });
          } else {
            let aaa = [
              {
                roleId: "",
                roleName: "",
                major: "1"
              }
            ];
            let bbb = [
              {
                vesselId: "",
                vesselName: ""
              }
            ];
            aaa = aaa.map(item => {
              return {
                ...item,
                roleId: this.editDeptInfo.roleId,
                roleName: this.editDeptInfo.roleName,
                deptName: this.editDeptInfo.deptName,
                deptId: this.editDeptInfo.deptId
              };
            });
            bbb = bbb.map(item => {
              return {
                ...item,
                vesselId: this.editDeptInfo.vesselId,
                vesselName: this.editDeptInfo.vesselName
              };
            });
            this.editDeptInfo.majorRoleId = this.editDeptInfo.roleId;
            this.editDeptInfo.roles = aaa;
            this.editDeptInfo.vessels = bbb;
            create(this.editDeptInfo)
              .then(response => {
                this.cancels();
                this.$message({
                  message: "保存成功",
                  type: "success"
                });
                this.getList();
              })
              .catch(err => {
                if (err === "MANAGEMENT_001") {
                  this.$message({
                    message: "当前用户名冲突!",
                    type: "warning"
                  });
                }
                if (err === "MANAGEMENT_002") {
                  this.$message({
                    message: "手机号冲突!",
                    type: "warning"
                  });
                }
                if (err === "MANAGEMENT_003") {
                  this.$message({
                    message: "邮箱冲突!",
                    type: "warning"
                  });
                }
                this.loadingSave = false;
              });
          }
        } else {
          this.$message({
            message: "带*号的为必填项！",
            type: "error"
          });
          return false;
        }
      });
    },
    getClear() {
      this.page.staffName = null;
      this.getList();
    },
    // 搜索
    oilInfoSearch() {
      this.getList();
    },
    // 添加成员
    addman() {
      this.editCompanyFlag = true;
      this.deptTitles = "添加成员";
      this.editDeptInfo = {
        loginPasswordAgain: '',
        staffAccount: ''
      };
      this.flag = true;
    },
    cancel() {
      this.addCompanyFlag = false;
      this.loadingSave = false;
    },
    cancels() {
      this.editCompanyFlag = false;
      this.loadingSave = false;
      this.flag = false;
    },
    getShoreDeptList() {
      shoreApi.compAndChildrenInfo().then(res => {
        res[0].children.unshift({
          compId: res[0].compId,
          compName: res[0].compName
        });
        this.companyList = res[0].children;
        this.companyList.unshift({
          compId: "",
          compName: "全部"
        });
      });
      this.loadingList = true;
      shoreApi.getDeptPageByCompId(this.page).then(response => {
        this.deptList = response.records;

        this.loadingList = false;
      });
    }
  }
};
</script>

<style scoped lang="scss">
.serviceType {
  /deep/.el-form-item__label {
    padding-right: 25px;
  }
  .el-form-item__content {
    position: relative;
  }
  .tips {
    font-size: 20px;
    color: #999;
    position: absolute;
    left: -25px;
    cursor: pointer;
    z-index: 99;
    &:hover {
      p {
        display: block;
      }
    }
    p {
      display: none;
      box-shadow: 0 1px 8px rgba(137, 142, 146, 0.34);
      font-size: 12px;
      line-height: 16px;
      background: #fff;
      color: #333;
      padding: 3px;
      margin: 0;
      margin-top: -4px;
      border-radius: 5px;
      height: 40px;
    }
  }
}
</style>
