<template>
  <div class="create-pages">
    <div class="create-bos">
      <div class="create-title flex-row-start">
        <el-icon color="#101828" size="16"><Document /></el-icon>
        <div style="margin-left: 6px">确认订单信息</div>
      </div>
      <div class="create-head flex-row-start">
        <span>{{ userStore.userInfo && userStore.userInfo.user ? userStore.userInfo.user.nickName : '' }}</span>
        <span class="border"></span>
        <span>{{ userStore.userInfo && userStore.userInfo.user ? userStore.userInfo.customerName : '' }}</span>
      </div>
      <div class="address-title">
        <div>收货地址</div>
        <el-button type="danger" link @click="handleAdd">
          <el-icon><Plus /></el-icon>新增收货地址
        </el-button>
      </div>
      <div class="address-bos">
        <div
          @click="onAddress(item)"
          v-for="(item, index) in addressList"
          :key="index"
          class="address-list flex-column-between"
          :class="item.id == form.shippingAddressId ? 'hig' : ''"
        >
          <div class="address1">{{ item.provincialCityCountry }}{{ item.address }}</div>
          <div class="address2">{{ item.consignee }}</div>
          <div class="address3">{{ item.phone }}</div>
        </div>
      </div>
      <div class="address-more flex-row-start">
        <!-- <div>展开全部地址</div>
        <el-icon style="margin-left: 6px" color="#6A7282" size="14"><ArrowDown /></el-icon> -->
      </div>
      <div class="form-bos" style="align-items: center">
        <div class="form-title flex-row-start">
          <div class="asterisk">*</div>
          <div>配送时间</div>
        </div>
        <el-date-picker
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 340px"
          v-model="form.deliveryDate"
          type="date"
          placeholder="选择日期"
          :disabled-date="disabledDate"
        />
      </div>
      <div class="form-bos" style="align-items: center">
        <div class="form-title flex-row-start">
          <div class="asterisk">*</div>
          <div>费用类型</div>
        </div>
        <el-select v-model="form.expenseType" placeholder="请选择费用类型" style="width: 340px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div class="form-bos">
        <div class="form-title flex-row-start">
          <div class="asterisk">*</div>
          <div>采购事由</div>
        </div>
        <el-input
          :maxlength="50"
          v-model="form.purchaseReason"
          style="width: 600px"
          :autosize="{ minRows: 4, maxRows: 8 }"
          type="textarea"
          show-word-limit
          placeholder="请输入采购事由"
        />
      </div>
      <div class="form-bos">
        <div class="form-title flex-row-start">
          <div class="asterisk"></div>
          <div>订单备注</div>
        </div>
        <el-input
          :maxlength="50"
          v-model="form.remark"
          style="width: 600px"
          :autosize="{ minRows: 4, maxRows: 8 }"
          type="textarea"
          show-word-limit
          placeholder="请输入订单备注"
        />
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{
          color: '#1D2129',
          backgroundColor: '#F2F3F5',
          fontWeight: 'normal'
        }"
      >
        <el-table-column label="商品信息" minWidth="650">
          <template #default="scope">
            <div class="cart-info">
              <img class="cart-img" :src="scope.row.productImage" alt="" />
              <div class="cart-text">
                <div class="text1">{{ scope.row.itemName }}</div>
                <div class="text2">
                  <span>单位:{{ scope.row.unitName }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" minWidth="150">
          <template #default="scope"> ¥{{ scope.row.memberPrice }} </template>
        </el-table-column>
        <el-table-column label="数量" minWidth="150">
          <template #default="scope"> {{ scope.row.productNum }} </template>
        </el-table-column>
        <el-table-column label="小计" minWidth="150">
          <template #default="scope"> ¥{{ (scope.row.memberPrice * scope.row.productNum).toFixed(2) }} </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="create-foot">
      <div class="foot-bos flex-row-between">
        <div></div>
        <div class="foot-box flex-column-between">
          <div class="flex-row-between" style="width: 100%">
            <div>商品件数</div>
            <div>{{ allNum }}</div>
          </div>
          <div class="flex-row-between" style="width: 100%">
            <div>商品总额</div>
            <div>¥{{ allMoney }}</div>
          </div>
          <div class="foot-yun flex-row-between">
            <div>运费</div>
            <div>¥0.00</div>
          </div>
          <div class="flex-row-between" style="width: 100%">
            <div>共计</div>
            <div class="zhu">¥{{ allMoney }}</div>
          </div>
          <div class="flex-row-between" style="width: 100%">
            <div></div>
            <div class="bnt-bos">
              <el-button @click="onPath('/cart')" class="bnt1">返回购物车修改</el-button>
              <el-button @click="onSubmit" class="bnt2" type="primary">提交订单</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" title="新增收货地址" width="550px">
      <el-form ref="formRef" :model="formAddress" :rules="rules" label-width="100px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="formAddress.name" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formAddress.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="formAddress.regionCodes"
            :options="regionData as any"
            placeholder="请选择省/市/区"
            style="width: 100%"
            @change="handleRegionChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formAddress.address" type="textarea" :rows="2" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="设为默认"><el-switch v-model="formAddress.isDefault" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getAddressList, addAddress } from '@/api/pc/enterprise';
import { shoppingCartList, pcOrdersubmit } from '@/api/goods/index';
import { onPath } from '@/utils/siteConfig';
import { regionData } from 'element-china-area-data';
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();
const route = useRoute();
const ids = ref<any>('');
const tableData = ref<any>([]);
const addressList = ref([]);
const allNum = ref(0);
const allMoney = ref<any>(0);
const form = ref<any>({
  shippingAddressId: '',
  deliveryDate: '',
  expenseType: '0',
  purchaseReason: '',
  remark: '',
  shippingFee: 0,
  // 下单方式  1为购物车下单  2为直接下单
  placeOrderType: 1,
  productShoppingCartId: []
});
const options = [
  {
    value: '0',
    label: '日常物资采购'
  }
];

//收货地址
const dialogVisible = ref(false);
const formRef = ref();
const formAddress = reactive({ name: '', phone: '', regionCodes: [], region: '', address: '', isDefault: false });
const rules = {
  name: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
};

onMounted(() => {
  ids.value = route.query.ids;
  form.value.productShoppingCartId = ids.value.split(',');
  loadAddressList();
  getCartList();
});
// 加载地址列表
const loadAddressList = async () => {
  try {
    const res = await getAddressList();
    if (res.code === 200) {
      addressList.value = res.rows || [];
      if (res.rows.length > 0) {
        form.value.shippingAddressId = res.rows[0].id;
        addressList.value.forEach((item: any) => {
          if (item.defaultAddress == 0) {
            form.value.shippingAddressId = item.id;
          }
        });
      }
    }
  } catch (error) {
    console.error('加载地址列表失败:', error);
    ElMessage.error('加载地址列表失败');
  }
};

//选择地址
const onAddress = (res: any) => {
  form.value.shippingAddressId = res.id;
};

//购物车
const getCartList = () => {
  const datas = { id: ids.value };
  shoppingCartList(datas).then((res) => {
    if (res.code == 200) {
      tableData.value = res.rows;
      res.rows.forEach((item: any) => {
        allNum.value = allNum.value + Number(item.productNum);
        allMoney.value = allMoney.value + Number(item.memberPrice * item.productNum);
      });
      allMoney.value = allMoney.value.toFixed(2);
    }
  });
};

const onSubmit = () => {
  if (!form.value.deliveryDate) {
    ElMessage.error('请选择配送时间');
    return;
  }
  if (!form.value.purchaseReason) {
    ElMessage.error('请输入采购事由');
    return;
  }
  pcOrdersubmit(form.value).then((res) => {
    if (res.code == 200) {
      onPath('/payc?id=' + res.data);
    }
  });
  console.log(form.value);
};

const handleAdd = () => {
  resetForm();
  dialogVisible.value = true;
};

const resetForm = () => {
  formAddress.name = '';
  formAddress.phone = '';
  formAddress.regionCodes = [];
  formAddress.region = '';
  formAddress.address = '';
  formAddress.isDefault = false;
};

// 处理地区选择变化
const handleRegionChange = (value: string[]) => {
  if (value && value.length === 3) {
    // 根据选中的代码查找对应的名称

    // 根据编码获取名称
    const names: string[] = [];
    if (value[0]) {
      const province = regionData.find((item: any) => item.value === value[0]);
      if (province) {
        names.push(province.label);

        if (value[1] && province.children) {
          const city = province.children.find((item: any) => item.value === value[1]);
          if (city) {
            names.push(city.label);

            if (value[2] && city.children) {
              const county = city.children.find((item: any) => item.value === value[2]);
              if (county) {
                names.push(county.label);
              }
            }
          }
        }
      }
    }

    // 将省市区名称用斜杠连接
    formAddress.region = names.join('/');
  }
};
const handleSave = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) return;
  try {
    const data: any = {
      consignee: formAddress.name,
      phone: formAddress.phone,
      address: formAddress.address,
      defaultAddress: formAddress.isDefault ? '0' : '1'
    };

    // 如果选择了省市区，发送代码
    if (formAddress.regionCodes && formAddress.regionCodes.length === 3) {
      data.provincialNo = formAddress.regionCodes[0];
      data.cityNo = formAddress.regionCodes[1];
      data.countryNo = formAddress.regionCodes[2];
      data.provincialCityCountry = formAddress.region;
    }

    await addAddress(data);
    ElMessage.success('新增成功');
    dialogVisible.value = false;
    loadAddressList();
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

const disabledDate = (date: Date) => {
  // 获取今天的零点时间戳
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 如果传入的日期 < 今天，则禁用 (返回 true)
  // 这样今天及以后的日期都会返回 false (可选)
  return date.getTime() < today.getTime();
};
</script>

<style lang="scss" scoped>
.create-pages {
  width: 100%;
  background-color: #ffffff;
  .create-bos {
    width: 100%;
    min-width: 1200px;
    max-width: 1500px;
    margin: 0 auto;
    .create-title {
      font-size: 16px;
      color: #101828;
      padding-top: 16px;
    }
    .create-head {
      width: 100%;
      min-width: 1200px;
      max-width: 1500px;
      height: 40px;
      background: #f9fafb;
      margin-top: 10px;
      font-weight: 600;
      font-size: 14px;
      color: #101828;
      padding-left: 10px;
      .border {
        display: inline-block;
        width: 1px;
        height: 12px;
        background-color: #e5e7eb;
        margin: 0 10px;
      }
    }
    .address-title {
      font-weight: 600;
      font-size: 14px;
      color: #101828;
      margin: 30px 0 10px 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .address-bos {
      display: flex;
      gap: 10px 12px;
      flex-wrap: wrap;
      .address-list {
        width: 291px;
        height: 92px;
        background: #ffffff;
        border-radius: 10px 10px 10px 10px;
        border: 1px solid #e5e7eb;
        padding: 12px;
        cursor: pointer;
        &.hig {
          border: 1px solid #e7000b;
        }
        .address1 {
          font-size: 14px;
          color: #364153;
        }
        .address2 {
          font-size: 14px;
          color: #101828;
        }
        .address3 {
          font-size: 14px;
          color: #364153;
        }
      }
    }
    .address-more {
      font-size: 14px;
      color: #6a7282;
      margin: 10px 0 30px 0;
    }
    .form-bos {
      margin-bottom: 20px;
      display: flex;
      align-items: start;
      .form-title {
        font-size: 14px;
        color: #1d2129;
        width: 80px;
        .asterisk {
          color: #f53f3f;
          width: 10px;
        }
      }

      :deep(.el-select__wrapper) {
        border: none;
        /* 可选：去除聚焦时的高亮 */
        box-shadow: none;
        outline: none;
        background: #f4f6f8;
      }
      :deep(.el-input__wrapper) {
        border: none;
        /* 可选：去除聚焦时的高亮 */
        box-shadow: none;
        outline: none;
        background: #f4f6f8;
      }
      :deep(.el-textarea__inner) {
        border: none;
        /* 可选：去除聚焦时的高亮 */
        box-shadow: none;
        outline: none;
        background: #f4f6f8;
      }
    }
    .cart-info {
      // width: 490px;
      height: 94px;
      display: flex;
      .cart-img {
        width: 94px;
        height: 94px;
        border-radius: 6px;
      }
      .cart-text {
        flex: 1;
        width: 0;
        padding-left: 10px;
        .text1 {
          font-size: 14px;
          color: #000000;
          height: 50px;
        }
        .text2 {
          font-size: 14px;
          color: #364153;
          span {
            margin-right: 10px;
          }
        }
        .text3 {
          font-size: 14px;
          color: #e7000b;
        }
      }
    }
  }
  .create-foot {
    width: 100%;
    height: 245px;
    background: #ffffff;
    box-shadow: 0px -2px 13px 0px rgba(0, 0, 0, 0.05);
    margin-top: 30px;
    .foot-bos {
      width: 1200px;
      margin: 0 auto;
      .foot-box {
        width: 458px;
        font-weight: 600;
        font-size: 14px;
        color: #101828;
        padding: 18px 0 20px 0;
        height: 245px;
        .foot-yun {
          width: 100%;
          height: 40px;
          background: #f7f8fc;
          border-radius: 10px;
          padding: 0 10px;
          font-weight: 400;
          font-size: 14px;
          color: #000000;
        }
        .zhu {
          color: #e7000b;
        }
        .bnt1 {
          width: 198px;
          height: 50px;
          background: #f7f8fa;
        }
        .bnt2 {
          width: 156px;
          height: 50px;
        }
      }
    }
  }
}
</style>
