<template>
    <NavBar :showIcon="true" :showTitle="true" title="我的公司" backgroundBox="#FFFFFF"></NavBar>
    <div class="page">
        <div class="content">
            <div class="top">
                <img v-if="params.logoPath" :src="evn.APP_IMAGE_BASE_API + params.logoPath" @click="chooseImage" />
                <img v-else src="@/static/image/temp/defaultCompany.png" alt="" @click="chooseImage" />
                <div class="name">{{ companyInfo.name }}</div>
                <formItem style="margin-top: 80rpx" title="营业执照" arrow :border="false" @click="jupmLicenseInfo">
                    <p :class="`status${companyInfo.companyAudit?.status}`">{{ auditStatus }}</p>
                </formItem>
            </div>
            <div class="form-wrap">
                <formItem title="企业简称">
                    <input type="text" v-model="params.nameAbbreviation" placeholder="请输入企业简称" />
                </formItem>
                <formItem title="公司所在地" arrow>
                    <wd-col-picker
                        v-model="cityValue"
                        :columns="cityOpstion"
                        value-key="code"
                        label-key="name"
                        :column-change="columnChangeCity"
                        @confirm="handleConfirmCity"
                        use-default-slot
                    >
                        <p :class="{ placeholder: !cityText }" class="text-single">{{ cityText || "请选择公司所在地" }}</p>
                    </wd-col-picker>
                </formItem>
                <formItem title="行业分类">
                    <p style="color: #77818f">{{ companyInfo.industryCategory }}</p>
                </formItem>
                <formItem title="详细地址">
                    <input type="text" placeholder="请输入详细地址" v-model="params.address" />
                </formItem>
                <div class="textarea-wrap">
                    <p class="label">公司介绍</p>
                    <textarea maxlength="500" placeholder="请输入公司介绍" v-model="params.companyIntro" />
                </div>
            </div>
        </div>
        <wd-tabbar
            @click="submit"
            custom-style="display: flex;justify-content: center !important;"
            fixed
            placeholder
            safeAreaInsetBottom
        >
            <view class="foot-btn">保存</view>
        </wd-tabbar>
    </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import formItem from "./formItem.vue";
import { getCompanyInfoApi, saveCompanyInfoApi } from "@/api/user";
import { getTreeListApi } from "@/api/common";
import { uploadFiles } from "@/utils/fileUpload";
import { getEnumText } from "@/utils/utils";
import evn from "@/utils/config";
import { useCompanyInfoStore } from "./companyInfo";

const params = reactive({
    id: 0,
    logoPath: "",
    nameAbbreviation: "",
    provinceCode: "",
    provinceName: "",
    cityCode: "",
    cityName: "",
    districtCode: "",
    districtName: "",
    address: "",
    companyIntro: ""
});
/* 调整到审核信息 */
const jupmLicenseInfo = () => {
    uni.navigateTo({
        url: "/pages/user/myCompany/licenseInfo"
    });
};
/* 审核状态文字 */
const auditStatus = ref("");
/* 获取公司信息 */
const companyInfo = ref({});
getCompanyInfoApi().then(async res => {
    const { setCompanyInfoValue } = useCompanyInfoStore();

    companyInfo.value = res.data;
    Object.keys(params).forEach(key => {
        params[key] = res.data[key];
    });
    const { provinceName, cityName, districtName } = res.data;

    cityText.value = [provinceName, cityName, districtName].join("-");
    // 审核状态
    auditStatus.value = await getEnumText("EnumAuditStatus", res.data.companyAudit.status);
    setCompanyInfoValue(res.data);
});
/* 获取省市区 */
const cityOpstion = ref([]);
const cityValue = ref([]);

const cityText = ref("");
let citySelectedItems = [];
getTreeListApi().then(res => {
    cityOpstion.value.push(res.data);
});
const columnChangeCity = ({ selectedItem, resolve, finish }) => {
    if (selectedItem.children) {
        resolve(selectedItem.children);
    } else {
        finish();
    }
};
const handleConfirmCity = ({ selectedItems }) => {
    cityText.value = selectedItems.map(v => v.name).join("-");
    citySelectedItems = selectedItems;
    const [province, city, district] = selectedItems;
    params.provinceCode = province.code;
    params.provinceName = province.name;
    params.cityCode = city.code;
    params.cityName = city.name;
    params.districtCode = district.code;
    params.districtName = district.name;
    console.log(cityValue);
};
/* 选择图片 */
const chooseImage = sourceType => {
    uni.chooseImage({
        sourceType: [sourceType],
        count: 1,
        success: async ({ tempFiles }) => {
            const res = await uploadFiles(tempFiles);
            params.logoPath = res[0].key;
        }
    });
};
/* 提交 */
const submit = () => {
    console.log(params);
    if (
        validateForm(params, [
            "address",
            "cityCode",
            "cityName",
            "companyIntro",
            "districtCode",
            "districtName",
            "id",
            "logoPath",
            "nameAbbreviation",
            "provinceCode",
            "provinceName"
        ])
    ) {
        saveCompanyInfoApi(params).then(res => {
            if (res.code == 200) {
                uni.showToast({
                    title: "保存成功",
                    icon: "success",
                    success() {
                        setTimeout(() => {
                            uni.navigateBack({
                                delta: 1
                            });
                        }, 1000);
                    }
                });
            } else {
                uni.showToast({
                    title: res.message,
                    icon: "none"
                });
            }
        });
    }
};

const validateForm = (formData, requiredFields) => {
    for (const field of requiredFields) {
        const value = formData[field];
        // 排除 0 和 "0" 的值，不作为空值校验
        if (value === undefined || value === null || value === "") {
            uni.showToast({
                title: `请填写完整表单`,
                icon: "none",
                duration: 2000
            });
            return false;
        }
    }
    return true;
};
</script>

<style lang="scss" scoped>
.page {
    display: flex;
    flex-direction: column;
    height: 100%;
    .content {
        flex: 1;
        .top {
            padding: 0 16px;
            text-align: center;
            border-bottom: 8px solid #f3f4f8;
            img {
                width: 80px;
                height: 80px;
                margin-top: 14px;
                border-radius: 50%;
            }
            .name {
                margin-top: 16px;
            }
            .status0 {
                color: #1f86ff;
            }
            .status1 {
                color: #31cbae;
            }
            .status2 {
                color: #ff5113;
            }
        }
        .form-item {
            text-align: left;
        }
        .form-wrap {
            padding: 0 16px;
            .placeholder {
                color: #77818f;
            }
            .textarea-wrap {
                padding: 16px 0;
                .label {
                    font-size: 12px;
                    font-weight: normal;
                    color: #77818f;
                }
                textarea {
                    box-sizing: border-box;
                    width: 343px;
                    height: 136px;
                    padding: 16px;
                    margin-top: 8px;
                    background: #f2f5fb;
                    border-radius: 4px;
                }
            }
        }
    }

    .foot-btn {
        position: fixed;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 622rpx;
        height: 80rpx;
        color: #ffffff;
        background: #1f86ff;
        border-radius: 12rpx;
    }
}
</style>
