<template>
  <view class="c-card">
    <u-form
      labelPosition="left"
      :model="model1"
      :rules="rules"
      ref="form"
      :labelWidth="100"
      :labelStyle="{ padding: '0rpx 10rpx' }"
      :errorType="'border-bottom'"
    >
      <u-form-item
        :prop="`formData.${item.key}`"
        :label="item.name"
        :required="item.required"
        v-for="(item, index) in formAttrList"
        :key="index"
        @click="item.fn"
      >
        <u-textarea
          v-if="item.type === 'textarea'"
          v-model="(model1.formData as any)[item.key]"
          :placeholder="`请输入${item.name}`"
        ></u-textarea>
        <u-input
          v-if="item.type === 'select' || item.type === 'input'"
          :password="item.name === 'password'"
          v-model="(model1.formData as any)[item.key]"
          :placeholder="`请${item.type === 'select' ? '选择' : '输入'}${
            item.name
          }`"
          :clearable="true"
          :customStyle="{}"
          border="none"
        >
          <template #suffix>
            <text>
              {{ item.unit }}
            </text>
          </template>
        </u-input>
        <template #right v-if="item.type === 'select'">
          <u-icon name="arrow-right"></u-icon>
        </template>
      </u-form-item>
    </u-form>
    <u-collapse>
      <u-collapse-item
        v-for="item in contrlModalParams.menu.list"
        :key="item.id"
        :title="item.name"
      >
        <view v-if="item.childrenList">
          <view
            v-for="cItem in item.childrenList"
            :key="cItem.id"
            class="flex-box"
          >
            <view>{{ cItem.name }}</view>
            <view>
              <u-switch
                size="18"
                activeColor="#00D2E3"
                v-model="cItem.checked"
              ></u-switch
            ></view> </view
        ></view>
        <view v-else>
          <u-empty mode="data"> </u-empty>
        </view>
      </u-collapse-item>
    </u-collapse>
    <!-- <block v-for="(item, index) in formAttrList" :key="index">
      <u-action-sheet
        v-if="item.type === 'select'"
        :actions="contrlModalParams[item.childKey].list"
        :title="contrlModalParams[item.childKey].title"
        :show="contrlModalParams[item.childKey].isShow"
        @select="(v: any) => handleSelect(item.childKey, v)"
        @close="contrlModalParams[item.childKey].isShow = false"
        :closeOnClickAction="true"
      ></u-action-sheet>
    </block> -->
  </view>
  <view class="btn-box">
    <u-button type="primary" text="保存" @click="save()"></u-button>
  </view>
</template>
<script setup lang="ts">
import { ProfileApi, StockCardApi } from "@/services";
import { deleteBaseKey, formatDate } from "@/utils";
import { DeviceType, ImagesType, OrderType, StockCardType } from "@/utils/enum";
import { onLoad } from "@dcloudio/uni-app";
import _ from "underscore";

const model1 = reactive<any>({
  formData: {},
});
const rules = ref({
  "formData.roleName": {
    type: "string",
    required: true,
    message: "请输入角色名称",
    trigger: ["blur", "change"],
  }
});
const contrlModalParams = reactive<any>({
  checkedMap: {},
  menu: {
    list: [],
  },
});

const formAttrList = reactive<any>([
  {
    name: "角色名称",
    key: "roleName",
    type: "input",
    required: true,
  },
  {
    name: "权限配置",
    key: "config",
    type: "text",
    childKey: "menu",
    fn: () => {},
  },
]);

// const handleSelect = (key: string, v: any) => {
//   contrlModalParams[key].isShow = false;
//   if (key === "role") {
//     model1.formData.roleName = v.name;
//     model1.formData.roleIds = [v.id];
//   }
// };
const form = ref();
const check = () => {
  return new Promise((resolve) => {
    form.value
      .validate()
      .then((res: boolean) => {
        resolve(res);
      })
      .catch((errors: any) => {
        resolve(false);
        uni.showToast({
          icon: "none",
          title: errors[0].message || "校验失败",
        });
      });
  });
};

const save = () => {
  check().then((res) => {
    if (res) {
      startSave();
    }
  });
};
const startSave = () => {
  let list: any = [];
  contrlModalParams.menu.list.forEach((item: any) => {
    item.childrenList.forEach((c: any) => {
      if (c.checked) {
        list.push({ menusId: c.id, state: c.checked ? 1 : 0 });
      }
    });
  });
  if (model1.formData.id) {
    ProfileApi.updateRole({ ...deleteBaseKey(model1.formData), list }).then(
      (res) => {
        if (res.code === 200) {
          uni.redirectTo({
            url: "/pagesApp/role", // 要跳转到的页面路径
          });
        }
      }
    );
  } else {
    ProfileApi.addRole({ ...model1.formData, list }).then((res) => {
      if (res.code === 200) {
        uni.redirectTo({
          url: "/pagesApp/role", // 要跳转到的页面路径
        });
      }
    });
  }
};

// 获得所有菜单
const getRoleList = () => {
  ProfileApi.getMenuList({}).then((res) => {
    if (res.code === 200) {
      contrlModalParams.menu.list = (res.data as any).map((item: any) => {
        item.childrenList = item.childrenList.map((cItem: any) => {
          console.log(contrlModalParams.checkedMap[cItem.id]);
          return {
            ...cItem,
            checked: contrlModalParams.checkedMap[cItem.id] ? true : false,
          };
        });
        return { ...item };
      });

      console.log(contrlModalParams.menu.list);
    }
  });
};

const getMenusRole = (roleId: number) => {
  ProfileApi.getMenusRole({ roleId }).then((res) => {
    if (res.data) {
      res.data.forEach((item: any) => {
        contrlModalParams.checkedMap[item.menusId] = item.state === 1;
      });
    }
  });
};

onMounted(() => {
  getRoleList();
});

onLoad((option) => {
  // 接收传递的标题参数;
  const title = (option as any).title;
  model1.formData = JSON.parse((option as any).item);
  if (model1.formData.id) {
    getMenusRole(model1.formData.id);
  }

  // 设置页面标题;
  if (title) {
    uni.setNavigationBarTitle({
      title: title,
    });
  }
});
</script>
<style lang="scss" scoped>
.c-card {
  background: #ffffff;
  // box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(5, 68, 37, 0.12);
  border-radius: 13rpx;
  margin: 30rpx 25rpx;
  padding: 0rpx 20rpx;
  ::v-deep .u-form-item {
    height: auto;
  }
  ::v-deep .u-form-item + .u-form-item {
    border-top: 1rpx solid rgba(233, 233, 233, 0.76);
  }
}
.btn-box {
  margin-top: 60rpx;
  display: flex;
  background: #ffffff;
  box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(0, 56, 93, 0.12);
  border-radius: 13rpx 13rpx 0rpx 0rpx;
  padding: 25rpx 50rpx;
  position: sticky;
  bottom: 0rpx;
  z-index: 999;
  ::v-deep button {
    border-radius: 43rpx;
  }
}
.flex-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.flex-box + .flex-box {
  margin-top: 20rpx;
}
</style>