<template>
  <div>
    <el-card class="!border-none" shadow="never">
      <el-page-header content="新增用户" @back="$router.back()" />
    </el-card>
    <el-card class="mt-4 !border-none" shadow="never">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="84px">
        <div style="font-size: 1.2rem; margin: 10px 0">基本信息创建</div>
        <div class="headimg">
          <el-upload v-model="formData.avatar" class="avatar-uploader-head" :data="{ cid: 1 }"
            :headers="{ Token: userStore.token }" :action="base_url + '/upload/image'" :show-file-list="false"
            :on-success="handleAvatarSuccessAvatar">
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
        <el-col class="pt-6 !border-none">
          <el-row>
            <!-- <el-col :span="11">
              <el-form-item label="公司" prop="company_name">
                <el-input
                  v-model="formData.company_name"
                  placeholder="请选择公司"
                  readonly
                  clearable
                  :style="{ width: '100%' }"
                  @click="showCompany = true"
                ></el-input>
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="13">
              <el-form-item label="角色" prop="group_id">
                <el-select
                  v-model="formData.group_id"
                  placeholder="请选择角色"
                  readonly
                  :style="{ width: '100%' }"
                  @change="formRef?.clearValidate(['group_id'])"
                >
                  <el-option
                    v-for="(item, index) in roleList"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="姓名" prop="nickname">
                <el-input v-model="formData.nickname" placeholder="请输入姓名" clearable :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">

              <el-form-item label="角色" prop="group_id">
                <el-select v-model="formData.group_id" placeholder="请选择角色" readonly :style="{ width: '100%' }"
                  @change="formRef?.clearValidate(['group_id'])">
                  <el-option v-for="(item, index) in roleList" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>

              <!-- <el-form-item label="性别" >
                <el-select
                  v-model="formData.sex"
                  placeholder="请选择性别"
                  :style="{ width: '100%' }"
                  @change="formRef?.clearValidate(['sex'])"
                >
                  <el-option label="男" :value="1" />
                  <el-option label="女" :value="2" />
                </el-select>
              </el-form-item> -->
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="11">
              <el-form-item label="联系电话" prop="account">
                <el-input v-model="formData.account" placeholder="请输入联系电话" clearable
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="身份证号">
                <el-input v-model="formData.id_card" placeholder="请输入身份证号" clearable
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
          </el-row>


          <el-row>
            <el-col :span="11">
              <el-form-item label="押金" >
                <el-input v-model="formData.deposit" placeholder="请输入押金" clearable type="number"
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <!-- <el-form-item label="角色" prop="group_id">
                <el-select
                  v-model="formData.group_id"
                  placeholder="请选择角色"
                  readonly
                  :style="{ width: '100%' }"
                  @change="formRef?.clearValidate(['group_id'])"
                >
                  <el-option
                    v-for="(item, index) in roleList"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item> -->
              <el-form-item label="押金缴纳时间" label-width="120px">
                <!-- <el-input v-model="formData.deposit_date" placeholder="请输入押金" clearable type="number"
                  :style="{ width: '100%' }"></el-input> -->



                  <el-date-picker  v-model="formData.deposit_date" style="width: 150%"   placeholder="请选择押金缴纳时间"  @change="dateChange" clearable></el-date-picker>
              </el-form-item>

              <!-- <el-form-item label="性别">
                <el-select v-model="formData.sex" placeholder="请选择性别" :style="{ width: '100%' }"
                  @change="formRef?.clearValidate(['sex'])">
                  <el-option label="男" :value="1" />
                  <el-option label="女" :value="2" />
                </el-select>
              </el-form-item> -->
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="管理户数" prop="user_information_count" label-width="200px">
                <el-input v-model="formData.user_information_count" placeholder="管理户数" clearable type="number"
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别">
                <el-select v-model="formData.sex" placeholder="请选择性别" :style="{ width: '100%' }"
                  @change="formRef?.clearValidate(['sex'])">
                  <el-option label="男" :value="1" />
                  <el-option label="女" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="13">
              <el-form-item label="角色" prop="group_id">
                <el-select
                  v-model="formData.group_id"
                  placeholder="请选择角色"
                  readonly
                  :style="{ width: '100%' }"
                  @change="formRef?.clearValidate(['group_id'])"
                >
                  <el-option
                    v-for="(item, index) in roleList"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="注册用户数" prop="register_num" label-width="200px">
                <el-input v-model="formData.register_num" placeholder="请输入" clearable type="number"
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入驻商户数" prop="merchant_num" label-width="100px">
                <el-input v-model="formData.merchant_num" placeholder="请输入" clearable type="number"
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="交易金额" prop="trade_amount" label-width="200px">
                <el-input v-model="formData.trade_amount" placeholder="请输入" clearable type="number"
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="邀请码" prop="invite_code" >
                <el-input v-model="formData.invite_code" placeholder="请输入" clearable type="number"
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-form-item label="省" prop="province" label-width="200px">
              <el-select v-model="formData.province" placeholder="请选择省" clearable @change="province_change"
                :style="{ width: '100%' }">
                <el-option v-for="(item, index) in datas.provinceOptions" :key="index" :label="item.province_name"
                  :value="item.province_code"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="市" prop="city">
              <el-select v-model="formData.city" placeholder="请选择市" clearable @change="city_change"
                :style="{ width: '100%' }">
                <el-option v-for="(item, index) in datas.cityOptions" :key="index" :label="item.city_name"
                  :value="item.city_code"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区县" prop="area">
              <el-select v-model="formData.area" placeholder="请选择区县" clearable @change="area_change"
                :style="{ width: '100%' }">
                <el-option v-for="(item, index) in datas.areaOptions" :key="index" :label="item.area_name"
                  :value="item.area_code"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="乡镇" prop="street">
              <el-select v-model="formData.street" placeholder="请选择乡镇" clearable @change="street_change"
                :style="{ width: '100%' }">
                <el-option v-for="(item, index) in datas.streetOptions" :key="index" :label="item.street_name"
                  :value="item.street_code"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="村社" prop="village">
              <el-select v-model="formData.village" placeholder="请选择村社" clearable @change="village_change"
                :style="{ width: '100%' }">
                <el-option v-for="(item, index) in datas.villageOptions" :key="index" :label="item.village_name"
                  :value="item.village_code"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="队/小区" prop="brigade" label-width="200px">
              <!-- <el-select v-model="formData.brigade" placeholder="请选择小队" clearable 
                :style="{ width: '100%' }" @change="brigadeChange">
                <el-option v-for="(item, index) in datas.brigadeOptions" :key="index" :label="item.brigade_name"
                  :value="item.id"></el-option>
              </el-select> -->
              <el-input v-model="formData.brigade" placeholder="请输入队/小区名称" clearable 
                  :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-row>
        </el-col>

        <div style="font-size: 1.2rem; margin: 10px 0">资质信息</div>
        <div style="display: flex; justify-content: space-between">
          <div>
            <el-form-item label="身份证">
              <el-upload v-model="formData.qualification.id_card" class="pl-3 avatar-uploader" :data="{ cid: 1 }"
                :headers="{ Token: userStore.token }" :action="base_url + '/upload/image'" :show-file-list="false"
                :on-success="handleAvatarSuccessIdA">
                <img v-if="formData.qualification.id_card" :src="formData.qualification.id_card" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
              <el-upload v-model="formData.qualification.id_card_b" class="pl-3 avatar-uploader" :data="{ cid: 1 }"
                :headers="{ Token: userStore.token }" :action="base_url + '/upload/image'" :show-file-list="false"
                :on-success="handleAvatarSuccessIdB">
                <img v-if="formData.qualification.id_card_b" :src="formData.qualification.id_card_b" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="银行卡">
              <el-upload v-model="formData.qualification.bank_account" class="pl-3 avatar-uploader" :data="{ cid: 1 }"
                :headers="{ Token: userStore.token }" :action="base_url + '/upload/image'" :show-file-list="false"
                :on-success="handleAvatarSuccessBankA" :before-upload="beforeAvatarUpload_three">
                <img v-if="formData.qualification.bank_account" :src="formData.qualification.bank_account"
                  class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
              <el-upload v-model="formData.qualification.bank_account_b" class="pl-3 avatar-uploader" :data="{ cid: 1 }"
                :headers="{ Token: userStore.token }" :action="base_url + '/upload/image'" :show-file-list="false"
                :on-success="handleAvatarSuccessBankB" :before-upload="beforeAvatarUpload_three">
                <img v-if="formData.qualification.bank_account_b" :src="formData.qualification.bank_account_b"
                  class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </div>

          <div>
            <el-form-item label="行驶证" prop="car_card">
              <el-upload v-model="formData.qualification.car_card" class="pl-3 avatar-uploader" :data="{ cid: 1 }"
                :headers="{ Token: userStore.token }" :action="base_url + '/upload/image'" :show-file-list="false"
                :on-success="handleAvatarSuccessCarA">
                <img v-if="formData.qualification.car_card" :src="formData.qualification.car_card" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
              <el-upload v-model="formData.qualification.car_card_b" class="pl-3 avatar-uploader" :data="{ cid: 1 }"
                :headers="{ Token: userStore.token }" :action="base_url + '/upload/image'" :show-file-list="false"
                :on-success="handleAvatarSuccessCarB" :before-upload="beforeAvatarUpload_two">
                <img v-if="formData.qualification.car_card_b" :src="formData.qualification.car_card_b" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </div>
        </div>
        <el-button type="primary" @click="submit">创建</el-button>
      </el-form>
    </el-card>
    <el-dialog v-model="showCompany">
      <DialogIndex :companyTypeList="datas.dictTypeLists" :type="41" @customEvent="customEvent"></DialogIndex>
    </el-dialog>
  </div>
</template>
  
<script lang="ts" setup name="consumerDetail">
import {
  type FormInstance,
  type UploadProps,
  ElMessage,
  type UploadUserFile,
} from "element-plus";
import {
  upContact,
  userAdd,
  getRolelist,
  getCompanyList,
} from "@/api/consumer";
import {
  apiCityList,
  apiAreaList,
  apiStreetList,
  apiProvinceList,
  apiVillageList,
  apiBrigadeList

} from "@/api/common";
import { dictDataLists } from "@/api/setting/dict";
import { isEmpty } from "@/utils/util";
import AccountAdjust from "../components/account-adjust.vue";
import useMultipleTabs from "@/hooks/useMultipleTabs";
import useUserStore from "@/stores/modules/user";
import feedback from "@/utils/feedback";
import DialogIndex from "./dialog_index.vue";
import { inject } from "vue";
const base_url: any = inject("base_url");
const { removeTab } = useMultipleTabs();
const router = useRouter();
const route = useRoute();
const flag = ref(true);
const formData = reactive({
  id: "",
  sex: "",
  id_card: "",
  nickname: "",
  group_id: "",
  company_id: 0,
  user_information_count: "",
  company_name: "",
  deposit_date: "",
  deposit: "",
  province: "",
  city: "",
  area: "",
  street: "",
  village: "",
  brigade: "",
  province_name: "",
  city_name: "",
  area_name: "",
  street_name: "",
  village_name: "",
  brigade_name: "",
  address: "",
  account: "",
  qualification: {
    id_card: "",
    id_card_b: "",
    car_card: "",
    car_card_b: "",
    bank_account: "",
    bank_account_b: "",
  },
  avatar: "",
  multipoint_login: 1,
  register_num:"",
  merchant_num:"",
  trade_amount :"",
  invite_code:""
});

const rules = ref({
  company_name: [{ required: true, message: "请选择公司", trigger: "blur" }],
  group_id: [{ required: true, message: "请选择角色", trigger: "blur" }],
  nickname: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  // sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
  // id_card: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
  account: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
  // "qualification.bank_account": [
  //   { required: true, message: "请上传银行卡", trigger: "blur" },
  // ],
  // "qualification.id_card": [
  //   { required: true, message: "请上传身份证", trigger: "blur" },
  // ],
});
const dateChange=()=>{
  let date=formData.deposit_date
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  formData.deposit_date=`${year}-${month}-${day}`
}
// 字典信息
const datas: any = reactive({
  provinceOptions: [],
  cityOptions: [],
  areaOptions: [],
  streetOptions: [],
  villageOptions:[],
  dictTypeLists: [],
  brigadeOptions:[],
  contract_type: [],
  contract: [],
});

const showCompany = ref(false);
const customEvent = (e: any) => {
  formData.company_id = e.id;
  formData.company_name = e.company_name;
  formData.province = e.province;
  formData.city = e.city;
  formData.area = e.area;
  formData.street = e.street;
  formData.village = e.village;
  formData.brigade = e.brigade;
  formData.province_name = e.province_name;
  formData.city_name = e.city_name;
  formData.area_name = e.area_name;
  formData.street_name = e.street_name;
  formData.village_name = e.village_name;
  formData.brigade_name = e.brigade_name;
  formRef.value?.clearValidate(["company_name"]);
  showCompany.value = false;
};

// 角色列表
const roleList = ref([]);
getRolelist({}).then((res: any) => {
  roleList.value = res;
});

const formRef = shallowRef<FormInstance>();
const isEdit = ref(false);

const userStore = useUserStore();

const fileList = ref<UploadUserFile[]>([]);
// 图片上传成功返回的url
const handleAvatarSuccessIdA: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.id_card = response.data.uri;
};
const handleAvatarSuccessAvatar: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.avatar = response.data.uri;
};
const handleAvatarSuccessIdB: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.id_card_b = response.data.uri;
};
const handleAvatarSuccessCarA: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.car_card = response.data.uri;
};
const handleAvatarSuccessCarB: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.car_card_b = response.data.uri;
};
const beforeAvatarUpload_two: UploadProps["beforeUpload"] = (rawFile) => {
  return true;
};
const handleAvatarSuccessBankA: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.bank_account = response.data.uri;
};
const handleAvatarSuccessBankB: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.bank_account_b = response.data.uri;
};
const handleAvatarSuccess_four: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.file = response.data.uri;
  upContact({ file: formData.file, id: route.query.mdoeid }).then((res) => [
    (mode.value = false),
  ]);
};
const beforeAvatarUpload_three: UploadProps["beforeUpload"] = (rawFile) => {
  return true;
};

//获取省份
function province_change(value: string) {
  console.log(formData)
  getCityList();
}
function city_change(value: string) {
  getAreaList();
}
function area_change(value: string) {
  getStreetList();
}
function street_change(value: string) {
  getVillageList()
  formData.street = value;
}
function village_change(value: string) {
  // getVillageList()
  getBrigadeList()
  // formData.street = value;
}
function brigadeChange(value: string) {
  // getVillageList()
  formData.brigade = value;
}


const getProvinceList = async () => {
  const data = await apiProvinceList({});
  datas["provinceOptions"] = data;
};
const getCityList = async () => {
  const data = await apiCityList({ city: formData.province });
  datas["cityOptions"] = data;
};
const getAreaList = async () => {
  const data = await apiAreaList({ area: formData.city });
  datas["areaOptions"] = data;
};
const getStreetList = async () => {
  const data = await apiStreetList({ street: formData.area });
  datas["streetOptions"] = data;
};
const getVillageList = async () => {
  const data = await apiVillageList({ village: formData.street });
  datas["villageOptions"] = data;

  // datas["streetOptions"] = data;
};
const getBrigadeList = async () => {
  const data = await apiBrigadeList({ brigade: formData.village });
  // datas["villageOptions"] = data;
  datas["brigadeOptions"] = data;


  // datas["streetOptions"] = data;
};


getProvinceList();

// 创建用户
const submit = () => {
  // if (!formData.avatar) return ElMessage.error("请上传头像");
  formRef.value?.validate((e) => {
    if (e) {
      // if (!formData.qualification.id_card || !formData.qualification.id_card_b)
      //   return ElMessage.error("请上传身份证信息");
      // if (
      //   !formData.qualification.bank_account ||
      //   !formData.qualification.bank_account_b
      // )
      //   return ElMessage.error("请上传银行卡信息");
      userAdd(formData).then(() => {
        ElMessage.success("添加成功");
        router.back();
      });
    }
  });
};
</script>
  
<style lang="scss">
.headimg {
  margin-top: 24px;
  width: 115px;
  height: 138px;
  float: left;
  overflow: hidden;
}

.avatar-uploader-head .el-upload {
  width: 115px;
  height: 138px;
  background-color: #fff;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload {
  width: 9.9vw;
  height: 6.3vw;
  background-color: #fff;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
  