<template>
  <div>
    <el-drawer
      class="edit-drawer"
      :title="isEdit ? '修改成员' : '新增成员'"
      size="40%"
      :visible.sync="visible"
      direction="rtl"
      :modal="modal"
      :wrapper-closable="false"
      @close="close"
    >
      <div v-if="!isEdit" class="page-tip-div" style="margin-top: 0">
        <span>温馨提示：</span>
        <span>
          新员工初始密码为
          <span style="color: #ff4400; font-weight: bold">88888888</span>
          ，登录后可修改密码。
        </span>
      </div>
      <el-form
        ref="form"
        :rules="rules"
        size="small"
        :model="form"
        label-width="120px"
      >
        <el-form-item label="姓名" prop="staffName">
          <el-input
            v-model="form.staffName"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="工号" prop="staffCode">
          <el-input
            v-model="form.staffCode"
            disabled
            placeholder="自动生成"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input
            v-model="form.mobile"
            placeholder="请输入手机号"
            max-length="11"
            :disabled="id"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="性别">
            <el-option label="男" :value="5"></el-option>
            <el-option label="女" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="age">
          <el-date-picker
            v-model="form.age"
            type="date"
            placeholder="选择生日"
            value-format="timestamp"
            default-value="1990-01-01"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-select v-model="form.education" placeholder="学历">
            <el-option
              v-for="(item, index) in education_list"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <span style="width: 265px; display: inline-block">
            <DepartmentSel
              v-model="department"
              :is-show-add="true"
              @change="departmentChange"
            />
          </span>
          <el-button
            v-if="systemType === 1"
            size="mini"
            type="text"
            @click="add_department = true"
          >
            【新建部门】
          </el-button>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <span style="width: 265px; display: inline-block">
            <RoleSelect
              v-model="role"
              :is-show-add="true"
              @change="roleChange"
            />
          </span>
          <el-button
            size="mini"
            type="text"
            class="add-role"
            @click="add_position = true"
          >
            【新增角色】
          </el-button>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="数据域权限">
          <el-radio-group v-model="form.dataField.dataField">
            <el-radio :label="1">本人</el-radio>
            <el-radio :label="2">用户</el-radio>
            <el-radio :label="3">所有</el-radio>
          </el-radio-group>

          <div v-if="form.dataField.dataField === 2">
            <el-tag
              v-for="(item, index) in staffName_arr"
              :key="index"
              closable
              @close="delStaff(index)"
            >
              {{ item.staffName }}
            </el-tag>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-plus"
              @click="staff_show = true"
            >
              用户
            </el-button>
          </div>
        </el-form-item>
        <el-form-item v-if="systemType === 1" label="店铺权限">
          <el-tag
            v-for="(item, index) in shop_arr"
            :key="index"
            type="primary"
            closable
            @close="delShop(index)"
          >
            {{ item.name }}
          </el-tag>
          <el-button size="small" type="primary" @click="show_shop = true">
            选择商铺
          </el-button>
          <el-button size="mini" type="text" @click="goShop()">
            【新建商铺】
          </el-button>
        </el-form-item>
        <el-form-item style="text-align: right; padding-right: 10px">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <el-button @click="close">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!--    </el-dialog>-->
    <GoodsChooseShop
      v-if="show_shop"
      :dialog-visible="show_shop"
      :is-show-add="true"
      :modal="false"
      @close="show_shop = false"
      @confirm="selShop"
    ></GoodsChooseShop>
    <!--    业务员-->
    <staffListModal
      v-if="staff_show"
      :modal="false"
      :is-show="staff_show"
      @cancel="staff_show = false"
      @confirm="staffSel"
    />
    <!--    新建部门-->
    <AddDepartment
      v-if="add_department"
      :modal="false"
      :visible="add_department"
      @close="add_department = false"
    />
    <!--    新增岗位/角色-->
    <el-dialog
      class="edit-drawer"
      title="新增角色"
      width="35%"
      :visible.sync="add_position"
      direction="rtl"
      :modal="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="drawerClose"
    >
      <AddPosition
        v-if="add_position"
        @confirm="add_position = false"
      ></AddPosition>
    </el-dialog>
  </div>
</template>

<script>
  import DepartmentSel from "@/component/common/DepartmentSel.vue";
  import RoleSelect from "@/component/common/RoleSelect.vue";
  import GoodsChooseShop from "@/component/goods/GoodsChooseShop.vue";
  import staffListModal from "@/component/common/staffListModal.vue";
  // 新增部门
  import AddDepartment from "@/component/SystemSettings/AddDepartment.vue";
  //  新增岗位/角色
  import AddPosition from "@/component/SystemSettings/AddPosition.vue";
  import { getStaffInfo, updateStaff, addStaff } from "@/api/Department";
  import { mapGetters } from "vuex";
  export default {
    name: "AddStaff",
    components: {
      DepartmentSel,
      RoleSelect,
      GoodsChooseShop,
      staffListModal,
      AddDepartment,
      AddPosition, // 新增角色
    },
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      isEdit: {
        type: Boolean,
        default: false,
      },
      id: {
        type: [Number, String],
        default: 0,
      },
      // 是否需要遮罩层
      modal: {
        type: Boolean,
        default: true,
      },
    },

    data() {
      return {
        add_position: false, // 新增角色
        shop_arr: [],
        staffName: "",
        staff_show: false,
        show_shop: false,
        add_department: false, // 新增部门
        // dataAccess: 1,
        customer_id: "",
        role: [],
        department: [],
        form: {
          departmentId: "",
          staffName: "",
          roleId: "",
          staffIdArr: [],
          mobile: "",
          email: "",
          staffCode: "",
          sex: "",
          age: "",
          education: "", // 学历
          departmentPidPath: "",
          rolePidPath: "",
          dataField: {
            dataField: 1,
            staffIds: [],
            shopIds: [],
          },
        },
        education_list: [
          {
            label: "大专以下",
            value: 1,
          },
          {
            label: "大专",
            value: 2,
          },
          {
            label: "本科",
            value: 3,
          },
          {
            label: "研究生",
            value: 4,
          },
          {
            label: "硕士",
            value: 5,
          },
          {
            label: "博士",
            value: 6,
          },
        ],
        Department_data: [],
        staffName_arr: [],
        rules: {
          staffName: [
            { required: true, message: "请输入部门名称", trigger: "blur" },
          ],
          departmentId: [
            { required: true, message: "请选择部门", trigger: "change" },
          ],
          roleId: [
            { required: true, message: "请选择角色", trigger: "change" },
          ],
          mobile: [{ required: true, message: "请输入手机", trigger: "blur" }],
          email: [
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"],
            },
          ],
        },
      };
    },
    computed: {
      ...mapGetters({
        storeData: "MUser/storeData",
      }),
    },
    created() {
      if (this.id) {
        this.getStaffInfo();
      }
    },
    methods: {
      goShop() {
        this.close();
        this.$emit("goShop");
        this.$router.push("/SystemSettings/liansuoguanli/AddShop");
      },
      // 关闭新增角色
      drawerClose() {
        this.add_position = false;
      },
      //  选择商铺
      selShop(row) {
        const arr = row.map((item) => {
          return {
            id: item.id,
            name: item.name,
          };
        });
        this.shop_arr = this.$_common.unique(this.shop_arr.concat(arr), ["id"]);
      },
      delShop(index) {
        this.shop_arr.splice(index, 1);
      },
      //  选择用户
      staffSel(row) {
        const arr = row.map((item) => {
          return {
            id: item.id,
            staffName: item.staffName,
          };
        });

        this.staffName_arr = this.$_common.unique(
          this.staffName_arr.concat(arr),
          ["id"]
        );
      },
      delStaff(index) {
        this.staffName_arr.splice(index, 1);
      },
      close() {
        this.$emit("close");
      },
      // 部门选择
      departmentChange(val) {
        this.form.departmentId = val.length ? val[val.length - 1] : "";
        this.form.departmentPidPath = val.join(",");
      },
      // 角色选择
      roleChange(val) {
        this.form.roleId = val.length ? val[val.length - 1] : "";
        this.form.rolePidPath = val.join(",");
      },
      //  详情 getStaffInfo
      async getStaffInfo() {
        if (!this.id) return;
        const { data } = await getStaffInfo(this.id);

        this.form = {
          ...data,
          departmentPidPath: data.extend.departmentPidPath,
          rolePidPath: data.extend.rolePidPath,
          age: data.age * 1000,
        };
        if (data.extend.rolePidPath) {
          this.role = data.extend.rolePidPath.split(",").map((item) => {
            return parseInt(item);
          });
        }

        this.department = data.extend.departmentPidPath
          .split(",")
          .map((item) => {
            return parseInt(item);
          });
        let shopArr = [];
        data.dataField.shopIds.forEach((item, index) => {
          shopArr.push({
            id: item,
            name: data.dataField.shopNames[index],
          });
        });
        this.shop_arr = shopArr;
        let arr = [];
        data.dataField.staffIds.forEach((item, index) => {
          arr.push({
            id: item,
            staffName: data.dataField.staffNames[index],
          });
        });
        this.staffName_arr = arr;
      },
      async confirm() {
        if (!this.form.staffName.trim()) {
          this.$message.warning("姓名不能为空");
          return;
        }
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            // let patten = /^([a-zA-Z0-9]+[_|_|\-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
            // if (this.form.email && patten.test(this.form.email)) {
            //   this.$message.warning("邮箱格式不正确");
            //   return;
            // }
            let target = {};
            this.form.dataField.staffIds = this.staffName_arr.map((item) => {
              return item.id;
            });
            // 区分多门店和总后台管理
            if (this.systemType === 1) {
              this.form.dataField.shopIds = this.shop_arr.map((item) => {
                return item.id;
              });
            } else {
              this.form.dataField.shopIds = [this.storeData.id];
            }

            const params = {
              departmentId: this.form.departmentId,
              staffName: this.form.staffName,
              roleId: this.form.roleId,
              mobile: this.form.mobile,
              email: this.form.email,
              staffCode: this.form.staffCode,
              sex: this.form.sex,
              age: this.form.age / 1000,
              education: this.form.education, // 学历
              departmentPidPath: this.form.departmentPidPath, // 添加部门id的数组
              rolePidPath: this.form.rolePidPath, // 添加角色id的数组
              dataField: this.form.dataField,
            };
            if (this.id) {
              target = await updateStaff(this.id, params);
            } else {
              target = await addStaff(params);
            }
            const data = target;

            if (this.id) {
              this.$message({
                message: "提交成功",
                type: "success",
              });
            } else {
              this.$message({
                message: data.data,
                type: "success",
              });
            }

            this.close();
            this.$emit("confirm");
          }
        });
      },
    },
  };
</script>

<style scoped>
  .btn-up {
    position: relative;
  }
  .btn-department {
    position: absolute;
    left: 270px;
    top: 4px;
  }
  .btn-role-up {
    position: relative;
  }
  .add-role {
    position: absolute;
    left: 270px;
    top: 4px;
  }
  .creat-shop {
    color: #1890ff;
    font-size: 12px;
  }
</style>
