import { CSSProperties, FC, PropsWithChildren, useState } from "react";
import "./index.less";
import { View, Form, Image, Text, Button, Picker } from "@tarojs/components";
import Container from "@/components/Container";
import joinIcon from "@/assets/images/kitchenWaste/join.svg";
import { useSetState } from "ahooks";
import cameraPng from "@/assets/images/kitchenWaste/camera.png";
import Taro, { useReady } from "@tarojs/taro";
import api from "@/services";
import serviceUrl from "@/services/core/api";
import clearIcon from "@/assets/images/kitchenWaste/clear.png";

interface FormItemProps {
  style?: CSSProperties;
  label: string;
}
export const FormItem: FC<PropsWithChildren<FormItemProps>> = ({
  children,
  style,
  label,
}) => {
  return (
    <View style={style}>
      <View className="form-item">
        <Text>{label}</Text>
      </View>
      {children}
    </View>
  );
};
/**
 * @description 添加商户
 */
const Record: FC = () => {
  const [selectedVehicle, setSelectedVehicle] = useState(0);
  const [selectedDate, setSelectedDate] = useSetState<Record<string, any>>({
    signTime: "",
    startTime: "",
    endTime: "",
  });
  const [contractImage, setContractImage] = useState<Record<string, any>[]>([]);
  const [vehicles, setVehicles] = useState<API.MerchantsListDot[]>([]);

  useReady(() => {
    api.kitchenWaste.getNotSignEntities().then((res) => {
      if (res.code === 200) {
        setVehicles(res.data);
      }
    });
  });

  //提交表单
  const formSubmit = (e) => {
    let { value } = e.target;

    for (let i in value) {
      if (!value[i]) {
        Taro.showToast({
          title: "请填写完整数据后再提交！",
          icon: "error",
          duration: 2000,
        });
        return;
      }
      if (["signTime", "startTime", "endTime"].includes(i)) {
        value[i] = value[i] + " 00:00:00";
      }
    }

    let params = {
      ...value,
      businessId: vehicles[value.businessName].value,
      businessName: vehicles[value.businessName].name,
      picture: contractImage.map((v) => v.id).join(","),
    };
    api.kitchenWaste.addWasteCollectionContract(params).then((res) => {
      if (res.code === 200) {
        Taro.showToast({
          title: "提交成功",
          icon: "success",
          duration: 2000,
          mask: true,
          success: () => {
            setTimeout(() => {
              Taro.navigateBack();
            }, 800);
          },
        });
      } else {
        Taro.showToast({
          title: res.msg ?? "",
          icon: "error",
          duration: 2000,
        });
      }
    });
  };

  const handleTakePhoto = () => {
    Taro.getSetting({
      success: (res) => {
        if (res.authSetting["scope.camera"]) {
          // 已经授权，直接调用相机
          takePhoto();
        } else {
          // 未授权，重新申请
          Taro.authorize({
            scope: "scope.camera",
            success: () => {
              takePhoto();
            },
            fail: () => {
              Taro.showModal({
                title: "提示",
                content: "需要您授权相机权限才能拍照，是否去设置？",
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    Taro.openSetting();
                  }
                },
              });
            },
          });
        }
      },
    });
  };

  const takePhoto = () => {
    Taro.chooseImage({
      count: 1,
      sourceType: ["album", "camera"],
      complete: (res: any) => {
        if (res.errMsg === "chooseImage:ok") {
          // 上传图片到服务器
          Taro.uploadFile({
            url: serviceUrl.authenticationUrl + "oss/upload?bucketName=xindu", // 替换为你的上传接口
            filePath: res.tempFilePaths[0], // 上传的图片文件路径
            name: "file", // 文件对应的 key（后端接收时的字段名）
            header: {
              "Content-Type": "multipart/form-data", // 设置请求头
              authorization: "Bearer " + Taro.getStorageSync("token"),
              "CLIENT-TOC": "Y",
            },
            success: (uploadResult) => {
              let upRes = JSON.parse(uploadResult.data);
              if (upRes.code === 200) {
                setContractImage([
                  ...contractImage,
                  {
                    url: res.tempFilePaths[0],
                    id: upRes.data,
                  },
                ]);
                Taro.showToast({
                  title: "拍照成功",
                  icon: "success",
                  duration: 2000,
                });
              } else {
                Taro.showToast({
                  title: "上传失败",
                  icon: "error",
                  duration: 2000,
                });
              }
            },
            fail: (err) => {
              console.log(err);
            },
          });
        }
      },
    });
  };

  const handlePreviewImage = (path: Record<string, string>) => {
    if (contractImage) {
      Taro.previewImage({
        current: path.url,
        urls: contractImage.map((v) => v.url),
      });
    }
  };

  return (
    <Container title="添加商户" style={{ backgroundColor: "#EEF7EF" }}>
      <View className="main">
        <Form onSubmit={formSubmit}>
          <FormItem label="商户名称">
            <Picker
              name="businessName"
              mode="selector"
              rangeKey="name"
              range={vehicles}
              onChange={(e: any) => {
                setSelectedVehicle(e.detail.value);
              }}
            >
              <View className="form-input">
                {selectedVehicle ? (
                  vehicles[selectedVehicle].name
                ) : (
                  <Text className="placeholder">请选择商户</Text>
                )}
                <View className="select-text">
                  请选择 <Image src={joinIcon} />
                </View>
              </View>
            </Picker>
          </FormItem>

          <FormItem label="合同起始时间" style={{ marginTop: 29 }}>
            <Picker
              name="startTime"
              mode="date"
              value={selectedDate.startTime}
              onChange={(e) => {
                setSelectedDate({ startTime: e.detail.value });
              }}
            >
              <View className="form-input">
                {selectedDate.startTime || (
                  <Text className="placeholder">请选择合同起始时间</Text>
                )}
                <View className="select-text">
                  请选择 <Image src={joinIcon} />
                </View>
              </View>
            </Picker>
          </FormItem>

          <FormItem label="合同终止时间" style={{ marginTop: 29 }}>
            <Picker
              name="endTime"
              mode="date"
              value={selectedDate.endTime}
              onChange={(e) => {
                setSelectedDate({ endTime: e.detail.value });
              }}
            >
              <View className="form-input">
                {selectedDate.endTime || (
                  <Text className="placeholder">请选择合同终止时间</Text>
                )}
                <View className="select-text">
                  请选择 <Image src={joinIcon} />
                </View>
              </View>
            </Picker>
          </FormItem>
          <FormItem label="签约时间" style={{ marginTop: 29 }}>
            <Picker
              name="signTime"
              mode="date"
              value={selectedDate.signTime}
              onChange={(e) => {
                setSelectedDate({
                  signTime: e.detail.value,
                });
              }}
            >
              <View className="form-input">
                {selectedDate.signTime || (
                  <Text className="placeholder">请选择签约时间</Text>
                )}
                <View className="select-text">
                  请选择 <Image src={joinIcon} />
                </View>
              </View>
            </Picker>
          </FormItem>

          <FormItem label="合同照片" style={{ marginTop: 29 }}>
            <View className="pt-box">
              {contractImage.map((v, index) => (
                <View className="cm-pt" key={"pt_" + index}>
                  <Image
                    onClick={handlePreviewImage.bind(this, v)}
                    src={v.url}
                    mode="aspectFit"
                    lazyLoad
                  />
                  <View
                    className="clear-item"
                    onTap={(e) => {
                      e.stopPropagation();
                      setContractImage((state) =>
                        state.filter((i) => i.id !== v.id)
                      );
                    }}
                  >
                    <Image src={clearIcon} />
                  </View>
                </View>
              ))}

              <View className="pictures-box" onTap={handleTakePhoto}>
                <Image src={cameraPng} />
                <View className="cam-text">
                  <Text>拍照上传</Text>
                </View>
              </View>
            </View>
          </FormItem>

          <Button formType="submit" className="sub-btn" plain>
            <Text>提交</Text>
          </Button>
        </Form>
      </View>
    </Container>
  );
};
export default Record;
