import { ScrollView, View, Text, Image } from "@tarojs/components";
import Taro from "@tarojs/taro";

import { useMemo } from "react";
import services from "@/services";
import { inversionSerializationRule } from "@/utils";
import { Form, Button, Flex } from "@taroify/core";
import RenderComponent from "@/components/CustomFormComponents/FormComponentRender";
import useGlobalStore from "@/store";
import LabelText from "./components/LabelText";
import "./index.less";
import icon14 from "@/assets/icon/icon14.png";

/** @name 审批 */
export default function () {
  const { userInfo, mainBodyInfo, projectFlowConfig, projectConfig } =
    useGlobalStore();

  const formConfig = useMemo(() => {
    const matterContentList = projectConfig?.matterContentList;

    if (matterContentList && projectFlowConfig?.examineKeys) {
      let temp = matterContentList
        .sort((pre: any, cur: any) => pre.sort - cur.sort)
        .map((item: any) => {
          return {
            ...item,
            componentOption: item.otherSet ? JSON.parse(item.otherSet) : {},
            key: item.fieldKey,
            validationRules: inversionSerializationRule(item.validationRules),
          };
        });

      /** 过滤需要处理的内容 */
      if (projectFlowConfig?.examineKeys !== "all") {
        const keys = projectFlowConfig?.examineKeys?.split(",") ?? [];
        temp = temp.filter((item: any) => keys.includes(item.fieldKey));
      }

      return temp;
    }
    return [];
  }, [projectConfig, projectFlowConfig]);

  const onSubmit = async (event: any) => {
    const values = event.detail.value;
    const mainBody = mainBodyInfo?.[0];
    const metaData = {
      thingId: projectConfig.id,
      name: projectConfig.thingName,
      loginName: userInfo?.mobile,
      applicantType: mainBody?.entityTypeId,
      applicantId: userInfo?.id,
      remake: "",
      subjectName: mainBody?.name,
      subjectCode: mainBody?.unifiedSocialCreditCode,
      subjectAddress: mainBody?.address,
      subjectContact: mainBody?.contactName,
      subjectPhone: mainBody?.phone,
      subjectStreet: mainBody?.streetCode,
    };
    let forms = [] as any[];
    const matterContentList = projectConfig?.matterContentList;

    for (const key in values) {
      const itemConfig = matterContentList.find((v: any) => v.fieldKey === key);
      if (itemConfig) {
        forms.push({
          reportName: userInfo?.nickname,
          contentId: key,
          content: values[key],
          downFlag:
            itemConfig.componentType === "FileUpload" ||
            itemConfig.componentType === "ImgUpload"
              ? true
              : false,
        });
      }
    }
    try {
      const { data: formId, code } = await services.approve.saveApplyItem({
        ...metaData,
        reportContents: forms,
      });
      if (code !== 200) {
        throw new Error();
      }
      const params = {
        businessId: formId,
        applicant: userInfo?.id,
        processId: projectConfig.processId,
      };

      const { data: taskId, code: code2 } = await services.approve.startExamine(
        params
      );
      if (code2 !== 200) {
        throw new Error();
      }

      const params2 = {
        taskId: taskId,
        user: userInfo?.id,
        approveComment: "已发起",
        streetId: mainBody?.streetCode,
      };

      const { code: code3 } = await services.approve.completeExamine(params2);

      if (code3 !== 200) {
        throw new Error();
      }

      Taro.navigateTo({
        url: "/pages/Success/index",
      });
    } catch {
      Taro.showToast({
        title: "提交失败",
        icon: "error",
      });
    }
  };

  return (
    <View className="container">
      <ScrollView scrollY className="manage_container">
        <View style={{ height: 24 }}></View>
        <View className="topCard">
          <Flex align="center">
            <Text style={{ color: "#fff" }}>{mainBodyInfo?.[0]?.name}</Text>
          </Flex>
          <LabelText
            label="组织机构代码"
            text={mainBodyInfo?.[0]?.unifiedSocialCreditCode}
          ></LabelText>
          <LabelText
            label="单位登记地址"
            text={mainBodyInfo?.[0]?.address}
          ></LabelText>
          <LabelText
            label="联系人"
            text={mainBodyInfo?.[0]?.contactName}
          ></LabelText>
          <LabelText
            label="联系电话"
            text={mainBodyInfo?.[0]?.phone}
          ></LabelText>
          <Image src={icon14} className="topCardImg"></Image>
        </View>

        <Form onSubmit={onSubmit}>
          <View className="formItemGroup">
            {formConfig.map((formItem) => {
              return (
                <Form.Item
                  name={formItem.key}
                  rules={[
                    {
                      required: formItem.componentOption?.require,
                      message: `请填写${formItem?.label}`,
                    },
                    ...formItem.validationRules,
                  ]}
                >
                  {formItem.componentType === "Branch" ? undefined : (
                    <Form.Label style={{ color: "#000", fontWeight: "bold" }}>
                      {formItem.label}
                    </Form.Label>
                  )}

                  <Form.Control>
                    {(controller) => (
                      <RenderComponent
                        config={formItem.componentOption}
                        componentType={formItem.componentType}
                        metaData={formItem}
                        {...controller}
                      ></RenderComponent>
                    )}
                  </Form.Control>
                </Form.Item>
              );
            })}
          </View>
          <Flex style={{ margin: "16px" }}>
            <Button shape="round" block color="primary" formType="submit">
              提交
            </Button>
          </Flex>
        </Form>
      </ScrollView>
    </View>
  );
}
