<template>
  <el-form :model="currentRow.data" :rules="editRules" label-width="120px" size="small" ref="editFormRef">
    <el-scrollbar height="350px" always style="
        padding: 10px 0;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
        margin-bottom: 20px;
      ">
      <el-form-item label="所属站点" prop="districtId">
        <div class="form-item">
          <district-screen v-model:districtId="currentRow.data.districtId" ref="districtScreenRef"
            :disabled="currentRow.data.id ? true : false" @districtChange="districtChange">
          </district-screen>
        </div>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <div class="form-item">
          <el-input v-model="currentRow.data.name" placeholder="请输入姓名"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <div class="form-item">
          <el-input v-model="currentRow.data.mobile" placeholder="请输入手机号"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <div class="form-item">
          <el-select v-model="currentRow.data.sex">
            <template v-for="item in selectItems['sex']" :key="item.key">
              <el-option :label="item.value" :value="item.key"></el-option>
            </template>
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <div class="form-item">
          <el-date-picker v-model="currentRow.data.birthday" type="date" placeholder="请选择" value-format="YYYY-MM-DD" />
        </div>
      </el-form-item>
      <el-form-item label="系统权限类型" prop="roleType">
        <div class="form-item">
          <el-select v-model="currentRow.data.roleType">
            <template v-for="item in selectItems['roleType']" :key="item.key">
              <el-option :label="item.value" :value="item.key"></el-option>
            </template>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="账号角色类型" prop="approle">
        <div class="form-item">
          <el-select v-model="currentRow.data.approle" :disabled="!currentRow.data.districtId">
            <template v-for="item in selectItems['approle']" :key="item.key">
              <el-option :label="item.value" :value="item.key"></el-option>
            </template>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="身份证号" prop="idcard">
        <div style="display: flex">
          <el-input style="width: 180px" v-model="currentRow.data.idcard" placeholder="请输入身份证号"></el-input>
          <span class="form-tip" style="color: red">注意：积分提现会涉及到</span>
        </div>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <div class="form-item">
          <el-input v-model="currentRow.data.email" placeholder="请输入邮箱"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="技能" prop="skills">
        <div>
          <el-select v-model="currentRow.data.skills" multiple clearable value-key="id">
            <template v-for="item in skills" :key="item.id">
              <el-option :label="item.skillName" :value="{ id: item.id, name: item.skillName }">
                <div>
                  <span class="custom-label" :style="{ background: item.colorValue }"></span>
                  <span>{{ item.skillName }}</span>
                </div>
              </el-option>
            </template>
          </el-select>
          <span @click="navTo('skillManage')" class="form-tip">未找到技能？点击此处添加</span>
        </div>
      </el-form-item>
      <el-form-item label="标签" prop="标签">
        <div>
          <el-select v-model="currentRow.data.labels" clearable multiple value-key="id">
            <template v-for="item in tags" :key="item.id">
              <el-option :label="item.labelName" :value="{ id: item.id, name: item.labelName }">
                <div>
                  <span class="custom-label" :style="{ background: item.colorValue }"></span>
                  <span>{{ item.labelName }}</span>
                </div>
              </el-option>
            </template>
          </el-select>
          <span @click="navTo('tagsManage')" class="form-tip">未找到标签？点击此处添加</span>
        </div>
      </el-form-item>
      <el-form-item label="聘用日期" prop="employDate">
        <div class="form-item">
          <el-date-picker v-model="currentRow.data.employDate" type="date" placeholder="请选择" clearable
            value-format="YYYY-MM-DD" />
        </div>
      </el-form-item>
      <el-form-item label="终止日期" prop="terminationDate">
        <div class="form-item">
          <el-date-picker v-model="currentRow.data.terminationDate" type="date" placeholder="请选择" clearable
            value-format="YYYY-MM-DD" />
        </div>
      </el-form-item>
      <el-form-item label="所属班组" prop="groups">
        <div class="form-item">
          <el-select v-model="currentRow.data.groups" clearable multiple value-key="id">
            <template v-for="item in groupData" :key="item.id">
              <el-option :label="item.name" :value="item"></el-option>
            </template>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="服务区域" prop="serviceAreas">
        <div class="form-item">
          <el-cascader :options="serviceAreaOptions" :props="serviceAreaProps" :show-all-levels="false" collapse-tags
            v-model="currentRow.data.serviceAreas" clearable ref="serviceAreasRef" />
        </div>
      </el-form-item>
      <el-form-item label="服务事项" prop="serviceEvents">
        <div class="form-item">
          <el-select v-model="currentRow.data.serviceEvents" multiple clearable value-key="id">
            <template v-for="item in eventData" :key="item.id">
              <el-option :label="item.name" :value="item"></el-option>
            </template>
          </el-select>
        </div>
      </el-form-item>
      <div style="display: flex;">
        <el-form-item label="上下班时间" prop="onTime"  
          :rules="
            currentRow.data.offTime
              ? [
                  {
                    required: true,
                    message: '请选择上班时间',
                    trigger: 'blur',
                  },
                  {
                    validator: verifyOnTime,
                  },
                ]
              : [
                  {
                    required: false,
                  },
                ]
          ">
          <div class="form-item" style="width: 83px;">
            <el-time-picker v-model="currentRow.data.onTime" range-separator="至" start-placeholder="上班时间"
              end-placeholder="下班时间" format="HH:mm" value-format="HH:mm" clearable />
          </div>
          <div style="margin: 0 3px; width: 6px; height: 2px; background-color: black;"></div>
        </el-form-item>
        <el-form-item label-width="0" prop="offTime" 
          :rules="
            currentRow.data.onTime
              ? [
                  {
                    required: true,
                    message: '请选择下班时间',
                    trigger: 'blur',
                  },
                  {
                    validator: verifyOffTime,
                  },
                ]
              : [
                  {
                    required: false,
                  },
                ]
          ">
          <div class="form-item" style="width: 85px;">
            <el-time-picker v-model="currentRow.data.offTime" range-separator="至" start-placeholder="上班时间"
              end-placeholder="下班时间" format="HH:mm" value-format="HH:mm" clearable />
          </div>
        </el-form-item>
      </div>
      <el-form-item label="备注" prop="note">
        <el-input type="textarea" placeholder="请输入备注信息（非必填），限500字以内" maxlength="500" autosize show-word-limit
          v-model="currentRow.data.note" :rows="5"></el-input>
      </el-form-item>
      <template v-if="approle == 5">
        <el-form-item label="站点功能设置" prop="districtMenu">
          <el-checkbox v-model="currentRow.data.districtMenuCheckAll" :indeterminate="currentRow.data.isIndeterminate"
            @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="currentRow.data.districtMenu" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in baseAppMenu" :key="item.appMenuId" :checked="item.state == 1" :label="item">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="个人功能设置" prop="myMenu">
          <el-checkbox v-model="currentRow.data.myMenuCheckAll" :indeterminate="currentRow.data.myMenuIsIndeterminate"
            @change="myMenuHandleCheckAllChange">全选
          </el-checkbox>
          <el-checkbox-group v-model="currentRow.data.myMenu" @change="myMenuHandleCheckedCitiesChange">
            <el-checkbox v-for="item in myBaseMenu" :key="item.myMenuId" :checked="item.state == 1" :label="item">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </template>
    </el-scrollbar>
    <el-form-item>
      <el-button @click="$emits('update:showEditForm', false)">取消</el-button>
      <el-button type="primary" @click="submit(editFormRef)">提交</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
export default {
  name: "user-set-from",
};
</script>
<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import templateHooks from "@/Hooks/templateHooks";
import {
  userService,
  skillService,
  tagService,
} from "@/ApiService/userCenterService.ts";
import { dropdownService } from "@/ApiService/dropdownService.js";
import { commonService } from "@/ApiService/commonService";
import { computed } from "@vue/reactivity";
const props = defineProps({
  currentRow: Object,
  showEditForm: Boolean,
  selectItems: Object,
});
const $emits = defineEmits(["update:showEditForm", "OK"]);
const editRules = reactive({
  districtId: [{ required: true, message: "请选择站点", trigger: "change" }],
  name: [{ required: true, message: "请输入姓名", trigger: "change" }],
  mobile: [{ required: true, message: "请输入手机号", trigger: "change" }],
  roleType: [
    { required: true, message: "请选择系统权限类型", trigger: "change" },
  ],
  approle: [
    { required: true, message: "请选择账号角色类型", trigger: "change" },
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  email: [
    {
      required: false,
      type: "email",
      message: "请输入合法的邮箱地址",
      trigger: "change",
    },
  ],
});
const serviceAreaProps = reactive({
  multiple: true,
  children: "childNode",
  checkStrictly: false,
  label: "name",
  value: "id",
  emitPath: false,
});
const serviceAreaOptions = ref([]);
const eventData = ref([]);
const groupData = ref([]);
const skills = computed(() => {
  return $common.fetchSkillsByDistrictId(props.currentRow.data.districtId);
});
const tags = computed(() => {
  return $common.fetchTagsByDistrictId(props.currentRow.data.districtId);
});
const serviceAreasRef = ref();
const editFormRef = ref();
const districtScreenRef = ref();
const approle = computed(() => {
  return props.currentRow.data.approle;
});
const comDistrictId = computed(() => {
  return props.currentRow.data.districtId;
});
const baseAppMenu = ref([]);
const myBaseMenu = ref([]);
// 数据定义 end
const submit = () => {
  // 提交时转化服务区域数据格式
  const serviceAreas = $common.formatServiceAreaData(serviceAreasRef);
  console.log(serviceAreas);
  let districtMenu = [];
  if (
    props.currentRow.data.districtMenu &&
    props.currentRow.data.districtMenu.length != 0
  ) {
    props.currentRow.data.districtMenu.map((item) => {
      districtMenu.push({ ...item, state: 1 });
    });
  }
  let myMenu = [];
  if (
    props.currentRow.data.myMenu &&
    props.currentRow.data.myMenu.length != 0
  ) {
    props.currentRow.data.myMenu.map((item) => {
      myMenu.push({ ...item, state: 1 });
    });
  }
  const {
    age,
    approle,
    birthday,
    districtId,
    email,
    employDate,
    groups,
    id,
    idcard,
    labels,
    mobile,
    name,
    note,
    roleType,
    serviceEvents,
    sex,
    skills,
    terminationDate,
    onTime,
    offTime,
  } = props.currentRow.data;
  editFormRef.value.validate((res) => {
    if (res) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
        .then(() => {
          userService
            .addOrUpdate({
              age,
              approle,
              birthday,
              districtId,
              email,
              employDate,
              groups,
              id,
              idcard,
              labels,
              mobile,
              name,
              note,
              roleType,
              serviceEvents,
              sex,
              skills,
              terminationDate,
              serviceAreas,
              districtMenu,
              myMenu,
              onTime,
              offTime,
            })
            .then((res) => {
              if (res.code == 0) {
                $emits("update:showEditForm", false);
                $message.success("操作成功");
                $emits("OK", true);
              } else {
                $message.error(res.err);
              }
            });
        });
    }
  });
};
const verifyOnTime = (rule, value, callback) => {
  if (value) {
    callback();
  } else {
    callback(new Error("请选择上班时间!"));
  }
};
const verifyOffTime = (rule, value, callback) => {
  if (value) {
    callback();
  } else {
    callback(new Error("请选择下班时间!"));
  }
};
// 获取服务区域
const fetchGridTree = () => {
  dropdownService
    .gridSceneTree({ districtId: props.currentRow.data.districtId })
    .then((res) => {
      if (res.code == 0) {
        serviceAreaOptions.value = res.data.childNode;
      } else {
        $message.error(res.err);
      }
    });
};
// 获取服务事项
const fetchMatter = () => {
  dropdownService
    .selectMatter({ districtId: props.currentRow.data.districtId })
    .then((res) => {
      if (res.code == 0) {
        eventData.value = res.data;
      } else {
        $message.error(res.err);
      }
    });
};
// 获取班组信息
const fetchWorkGroup = () => {
  dropdownService
    .selectWorkGroup({ districtId: props.currentRow.data.districtId })
    .then((res) => {
      if (res.code == 0) {
        groupData.value = res.data;
      } else {
        $message.error(res.err);
      }
    });
};

// 跳转方法
const navTo = (type) => {
  if (!props.currentRow.data.districtId) {
    $message.error("请选择所属站点");
    return;
  }
  const path = "/userCenter/" + type;
  commonService.getIdByPath({ path }).then((res) => {
    if (res.code == 0) {
      $router.push({
        path,
        query: {
          pageType: 0,
          wId: res.data,
          districtId: props.currentRow.data.districtId,
        },
      });
    } else {
      $message.error(res.err);
    }
  });
};
// 监听站点变化
const districtChange = (districtId) => {
  console.log("父组件districtId", districtId);
  const labels = [
    "skills",
    "labels",
    "groups",
    "serviceAreas",
    "serviceEvents",
  ];
  for (let i in labels) {
    props.currentRow.data[labels[i]] = [];
  }

  if (districtId) {
    fetchGridTree();
    fetchMatter();
    fetchWorkGroup();
    $store.dispatch("fetchTags", { districtId });
    $store.dispatch("fetchSkills", { districtId });
  } else {
    // 清空站点时 清空关联项数据源
    groupData.value = [];
    eventData.value = [];
    serviceAreaOptions.value = [];
  }
};
// 增加时获取站点基本功能
const fetchBaseAPPMenu = () => {
  userService
    .getBaseAppMenu({ districtId: comDistrictId.value })
    .then((res) => {
      if (res.code == 0) {
        baseAppMenu.value = res.data;
      } else {
        $message.error(res.err);
      }
    });
};
// 增加时获取个人功能
const fetchMyBaseMenu = () => {
  userService.getMyBaseMenu({ districtId: comDistrictId.value }).then((res) => {
    if (res.code == 0) {
      myBaseMenu.value = res.data;
    } else {
      $message.error(res.err);
    }
  });
};
// 编辑时获取站点基本功能
const getDistrictAppMenu = () => {
  userService
    .getDistrictAppMenu({
      districtId: comDistrictId.value,
      userId: props.currentRow.data.id,
    })
    .then((res) => {
      if (res.code == 0) {
        baseAppMenu.value = res.data;
        let districtMenu = [];
        baseAppMenu.value.map((item) => {
          if (item.state == 1) {
            districtMenu.push(item);
          }
        });
        props.currentRow.data.districtMenu = districtMenu;
        props.currentRow.data.districtMenuCheckAll =
          districtMenu.length === baseAppMenu.value.length;
        props.currentRow.data.isIndeterminate =
          districtMenu.length > 0 &&
          districtMenu.length < baseAppMenu.value.length;
      } else {
        $message.error(res.err);
      }
    });
};
// 编辑时获取个人功能
const getMyMenu = () => {
  userService.getMyMenu({ userId: props.currentRow.data.id }).then((res) => {
    if (res.code == 0) {
      myBaseMenu.value = res.data;
      let myMenu = [];
      myBaseMenu.value.map((item) => {
        if (item.state == 1) {
          myMenu.push(item);
        }
      });
      props.currentRow.data.myMenu = myMenu;
      props.currentRow.data.myMenuCheckAll =
        myMenu.length === myBaseMenu.value.length;
      props.currentRow.data.myMenuIsIndeterminate =
        myMenu.length > 0 && myMenu.length < myBaseMenu.value.length;
    } else {
      $message.error(res.err);
    }
  });
};
// 站点基本功能全选按钮点击时触发
const handleCheckAllChange = (val) => {
  props.currentRow.data.districtMenu = val ? baseAppMenu.value : [];
  props.currentRow.data.isIndeterminate = false;
};
// 站点基本功能选项变化触发
const handleCheckedCitiesChange = (obj) => {
  const checkedCount = obj.length;
  props.currentRow.data.districtMenuCheckAll =
    checkedCount === baseAppMenu.value.length;
  props.currentRow.data.isIndeterminate =
    checkedCount > 0 && checkedCount < baseAppMenu.value.length;
};
// 个人基本功能全选按钮点击时触发
const myMenuHandleCheckAllChange = (val) => {
  props.currentRow.data.myMenu = val ? myBaseMenu.value : [];
  props.currentRow.data.myMenuIsIndeterminate = false;
};
// 个人基本功能选项变化触发
const myMenuHandleCheckedCitiesChange = (obj) => {
  const checkedCount = obj.length;
  props.currentRow.data.myMenuCheckAll =
    checkedCount === myBaseMenu.value.length;
  props.currentRow.data.myMenuIsIndeterminate =
    checkedCount > 0 && checkedCount < myBaseMenu.value.length;
};
const { $router, $store, selectItems, $common, $message, $messageBox } =
  templateHooks();
// 函数定义 end
onMounted(() => {
  districtScreenRef.value.fetchDistricts();
  if (props.currentRow.data.districtId) {
    fetchGridTree();
    fetchMatter();
    fetchWorkGroup();
    $store.dispatch("fetchTags", {
      districtId: props.currentRow.data.districtId,
    });
    $store.dispatch("fetchSkills", {
      districtId: props.currentRow.data.districtId,
    });
    getDistrictAppMenu();
    getMyMenu();
  }
});
watch(approle, (val) => {
  if (val == 5) {
    if (!props.currentRow.data.id) {
      fetchBaseAPPMenu();
      fetchMyBaseMenu();
    } else {
      getDistrictAppMenu();
      getMyMenu();
    }
  } else {
  }
});
// 生命周期 end
</script>
<style lang="scss" scoped>
.custom-label {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 100%;
  margin-right: 5px;
}
</style>
