<template>
  <u-sticky class="shadow-default" bgColor="#fff" style="top: 0">
    <u-navbar :titleStyle="{ color: '#000' }" :autoBack="true" :title="pageTitle" :placeholder="true" :safeAreaInsetTop="true" bgColor="#fff">
      <template #left>
        <view class="u-navbar__content__left__item">
          <u-icon name="arrow-left" size="20" color="#000"></u-icon>
        </view>
      </template>
    </u-navbar>
  </u-sticky>

  <oa-scroll
    customClass="record-container scroll-height"
    :isSticky="false"
    :customStyle="{
      //#ifdef APP-PLUS || MP-WEIXIN
      height: 'calc(100vh - 44px)',
      //#endif
    }"
    :refresherLoad="false"
    :refresherEnabled="false"
    :refresherDefaultStyle="'none'"
    :refresherThreshold="44"
    :lowerThreshold="44"
    :refresherBackground="'#f5f6f7'"
    :data-theme="'theme-' + proxy.$settingStore.themeColor.name"
  >
    <template #default>
      <view class="content-area">
        <view class="content-area-item mt10 p10 bg-white">
          <view class="font14 weight mb10 required">项目名称</view>
          <u-input v-model="form.projectName" placeholder="请输入" fontSize="14px" placeholderStyle="color:#909399;font-size:12px" border="none"> </u-input>
        </view>
        <view class="content-area-item mt10 p10 bg-white">
          <view class="font14 weight mb10 required">项目类型</view>
          <u-input
            :modelValue="proxy.$common.mapping('label', 'value', form.projectType, project_type)"
            fontSize="14px"
            placeholderStyle="color:#909399;font-size:12px"
            placeholder="请选择"
            border="none"
            disabledColor="transparent"
            disabled
          />
          <u-button class="mt20" type="primary" style="width: 100px; height: 25px" @click="handleAction('项目类型', project_type)" shape="circle" icon="plus" size="mini"> 选择项目类型 </u-button>
        </view>
        <view class="content-area-item mt10 p10 bg-white">
          <view class="font14 weight mb10 required">项目状态</view>
          <u-input
            :modelValue="proxy.$common.mapping('label', 'value', form.projectStatus, project_status)"
            fontSize="14px"
            placeholderStyle="color:#909399;font-size:12px"
            placeholder="请选择"
            border="none"
            disabledColor="transparent"
            disabled
          />
          <u-button class="mt20" type="primary" style="width: 100px; height: 25px" @click="handleAction('项目状态', project_status)" shape="circle" icon="plus" size="mini"> 选择项目状态 </u-button>
        </view>
        <view class="content-area-item mt10 p10 bg-white">
          <view class="font14 weight mb10 required">项目负责人</view>
          <avatarList :userList="projectHeadList" @deleteUsers="(value) => deleteUsers(value, 'projectHeadList')" />
          <u-button class="mt20" type="primary" style="width: 100px; height: 25px" @click="insertUsers('projectHeadList')" shape="circle" icon="plus" size="mini"> 选择项目负责人 </u-button>
        </view>
        <view class="content-area-item mt10 p10 bg-white">
          <view class="font14 weight mb10">计划人/天</view>
          <u-input v-model="form.projectWorkload" placeholder="请输入" fontSize="14px" placeholderStyle="color:#909399;font-size:12px" type="digit" border="none"> </u-input>
        </view>
        <view class="content-area-item mt10 p10 bg-white">
          <view class="font14 weight mb10">项目成员</view>
          <avatarList :userList="projectMemberList" @deleteUsers="(value) => deleteUsers(value, 'projectMemberList')" />
          <u-button class="mt20" type="primary" style="width: 100px; height: 25px" @click="insertUsers('projectMemberList')" shape="circle" icon="plus" size="mini"> 选择项目成员 </u-button>
        </view>
        <view class="content-area-item mt10 p10 bg-white">
          <view class="font14 weight mb10">项目描述</view>
          <u-textarea
            v-model="form.projectDescribe"
            placeholder="请输入"
            placeholderStyle="color:#909399;font-size:12px"
            confirmType="return"
            :autoHeight="true"
            :maxlength="-1"
            :height="'100%'"
            border="none"
            style="padding: 0px"
            @change="realTimeSaving()"
          ></u-textarea>
        </view>
      </view>

      <view class="app-button">
        <view class="app-button-padding"></view>
        <view class="app-button-fixed">
          <u-button class="app-buttom" type="primary" @click="handleSubmit('提交')" shape="circle"> 提交 </u-button>
        </view>
      </view>
    </template>
  </oa-scroll>

  <u-picker
    :show="actionShow"
    :columns="actionsList"
    :title="'请选择' + actionTitle"
    keyName="label"
    visibleItemCount="6"
    :defaultIndex="[actionDefaultIndex]"
    :closeOnClickOverlay="true"
    @close="actionShow = false"
    @cancel="actionShow = false"
    @confirm="selectAction"
  ></u-picker>
</template>

<script setup>
/*----------------------------------依赖引入-----------------------------------*/
import { onLoad, onShow, onReady, onHide, onLaunch, onUnload, onNavigationBarButtonTap, onPageScroll } from "@dcloudio/uni-app";
import { ref, reactive, computed, getCurrentInstance, toRefs, inject } from "vue";
/*----------------------------------接口引入-----------------------------------*/
import { projectApi } from "@/api/business/project.js";
import { dUserList } from "@/api/system/user.js";
/*----------------------------------组件引入-----------------------------------*/
import avatarList from "../components/avatarList.vue";
/*----------------------------------store引入-----------------------------------*/
import { systemStores } from "@/store/modules/index";
/*----------------------------------公共方法引入-----------------------------------*/
import { storageSystem } from "@/utils/storage"; // 公共方法引用
/*----------------------------------公共变量-----------------------------------*/
const systemStore = systemStores();
const { proxy } = getCurrentInstance();
const { project_status, project_type, project_ascription } = proxy.useDict("project_status", "project_type", "project_ascription");
const props = defineProps({
  id: {
    type: String,
    default: undefined,
  },
});
/*----------------------------------变量声明-----------------------------------*/
const uForm = ref(null);
const state = reactive({
  pageTitle: "",
  userDate: [],
  projectKey: "",
  projectHeadList: [],
  projectMemberList: [],
  form: {
    projectId: undefined,
    projectName: "", //项目名称
    projectType: undefined, //项目类型
    projectStatus: undefined, //项目状态
    projectWorkload: "", //计划人/天
    projectHead: undefined, //项目负责人
    projectMember: "", //项目成员
    projectDescribe: "", //项目描述
    // startTime: "2022-10-01T01:00:00",
    // endTime: "2023-03-31T23:59:59",
  },

  actionShow: false,
  actionTitle: "",
  actionsList: [],
  actionDefaultIndex: 0,
});

const { pageTitle, projectHeadList, projectMemberList, form, rules, actionShow, actionTitle, actionsList, actionDefaultIndex } = toRefs(state);

/** 添加人员按钮事件 */
function insertUsers(key) {
  state.projectKey = key;
  //将人员选中数据传入store中
  systemStore.mallList.activeUserList = state[key];
  if (key === "projectHeadList") {
    proxy.$tab.navigateTo(`/pages/business/common/projectMange/mall/index?number=1&type=1`);
  } else if (key === "projectMemberList") {
    proxy.$tab.navigateTo(`/pages/business/common/projectMange/mall/index?number=50&type=2`);
  }
}

/** 删除人员按钮事件 */
function deleteUsers(index, key) {
  state[key].splice(index, 1);
}

/**
 * @action弹出框点击事件
 */
function handleAction(title, event, index, ind) {
  state.actionTitle = title;
  state.actionIndex = index;
  state.actionsList[0] = event;
  state.actionDefaultIndex = 0;
  state.actionShow = true;
}

/**
 * @action弹出框选择事件
 */
function selectAction(e) {
  if (state.actionTitle == "项目类型") {
    state.form.projectType = e.value[0].value; //项目名称
  } else if (state.actionTitle == "项目状态") {
    state.form.projectStatus = e.value[0].value; //项目名称
  }
  state.actionShow = false;
}

/**
 * @列表查询
 * @api接口查询
 */
function selectListApi() {
  projectApi()
    .ProjectsList({
      projectId: parseInt(props.id),
      pageNum: 1,
      pageSize: 20,
    })
    .then((requset) => {
      if (requset.data.records.length > 0) {
        const data = requset.data.records[0];
        state.form.projectId = data.id;
        state.form.projectName = data.projectName;
        state.form.projectType = data.projectType;
        state.form.projectStatus = data.projectStatus;
        state.form.projectWorkload = data.projectWorkload ? data.projectWorkload : "";
        state.form.projectHead = data.projectHead;
        state.form.projectMember = data.projectMember;
        state.form.projectDescribe = data.projectDescribe;
      }

      var projectMember = state.form.projectMember.length > 0 ? state.form.projectMember.split(",").map((num) => Number(num)) : [];
      state.userDate.forEach((e) => {
        if (projectMember.includes(e.userId)) {
          state.projectMemberList.push({
            address: e.address,
            avatar: e.avatar,
            deptId: e.deptId,
            email: e.email,
            id: e.userId,
            label: e.nickName,
            nickName: e.nickName,
            phonenumber: e.phonenumber,
            post: e.post,
            sex: e.sex,
            userId: e.userId,
            userName: e.userName,
          });
        }

        var projectHead = state.form.projectHead ? [state.form.projectHead] : [];
        if (projectHead.includes(e.userId)) {
          state.projectHeadList.push({
            address: e.address,
            avatar: e.avatar,
            deptId: e.deptId,
            email: e.email,
            id: e.userId,
            label: e.nickName,
            nickName: e.nickName,
            phonenumber: e.phonenumber,
            post: e.post,
            sex: e.sex,
            userId: e.userId,
            userName: e.userName,
          });
        }
      });
    })
    .catch((err) => {});
}

/**
 * @提交
 */
function handleSubmit(value) {
  if (!state.form.projectName) {
    proxy.$modal.msg("请输入项目名称！");
    return;
  }
  if (!state.form.projectType) {
    proxy.$modal.msg("请选择项目类型！");
    return;
  }
  if (!state.form.projectStatus) {
    proxy.$modal.msg("请选择项目状态！");
    return;
  }
  if (state.projectHeadList.length <= 0) {
    proxy.$modal.msg("请选择项目负责人！");
    return;
  }

  state.form.projectHead = state.projectHeadList[0].id;
  state.form.projectMember = state.projectMemberList.map((obj) => `${obj.id}`).join(",");

  proxy.$modal.loading("加载中");
  projectApi()
    .ProjectsInsertUpdate({
      id: state.form.projectId,
      projectName: state.form.projectName, //项目名称
      projectType: state.form.projectType, //项目类型
      projectStatus: state.form.projectStatus, //项目状态
      projectWorkload: state.form.projectWorkload, //计划人/天
      projectHead: state.form.projectHead, //项目负责人
      projectMember: state.form.projectMember, //项目成员
      projectDescribe: state.form.projectDescribe, //项目描述
      // startTime: "2022-10-01T01:00:00",
      // endTime: "2023-03-31T23:59:59",
    })
    .then(() => {
      state.projectKey = "";
      state.projectHeadList = [];
      state.projectMemberList = [];
      state.form = {
        projectId: undefined,
        projectName: "", //项目名称
        projectType: undefined, //项目类型
        projectStatus: undefined, //项目状态
        projectWorkload: "", //计划人/天
        projectHead: undefined, //项目负责人
        projectMember: "", //项目成员
        projectDescribe: "", //项目描述
        // startTime: "2022-10-01T01:00:00",
        // endTime: "2023-03-31T23:59:59",
      };
      proxy.$modal.closeLoading();
      proxy.$modal.msg("提交成功");
      proxy.$tab.navigateBack(1); //返回到需要执行方法的页面
    })
    .catch((errors) => {
      proxy.$modal.closeLoading();
      proxy.$modal.msg("提交失败，请稍后重试！");
    });
}

onLoad((options) => {
  dUserList().then((res) => {
    state.userDate = res.data;
  });

  if ("id" in options) {
    state.pageTitle = "项目编辑";
    selectListApi();
  } else {
    state.pageTitle = "项目新增";
  }
});

onReady(() => {});

onShow(() => {
  //调用系统主题颜色
  proxy.$settingStore.systemThemeColor([1]);

  //监听组件返回数据
  uni.$on("UserMall", function (value) {
    console.log(value);
    state[state.projectKey] = value;
  });
});

onUnload(() => {
  uni.$off("UserMall"); //将值删除监听器
});
</script>

<style lang="scss" scoped>
:deep() {
  .u-cell__body {
    color: #000000;
    font-size: 12px;
    padding: 10px 0px !important;
  }
  .u-collapse-item__content {
    overflow: auto;
  }
  .u-collapse-item__content__text {
    padding: 0;
  }
  .u-cell__left-icon-wrap {
    margin: 0;
  }
}
.content-area {
  &-title {
    text-align: right;
    color: #909399;
  }
}
</style>
