<template>
  <div class="app-container">
    <!-- 添加一个加载状态，在获取createOrderType之前显示 -->
    <div v-if="!formReady" style="text-align: center; padding: 50px;">
      <i class="el-icon-loading"></i> 正在加载...
    </div>

    <!-- 只有在formReady为true时才显示表单 -->
    <el-form v-if="formReady" ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="会员信息" prop="userId">
        <el-table border style="margin-top:5px;" v-loading="userloading" :data="users">
          <el-table-column label="ID" align="center" prop="userId" />
          <el-table-column label="会员头像" align="center" width="80">
            <template slot-scope="scope">
              <el-popover placement="right" title="" trigger="hover">
                <img slot="reference" :src="scope.row.avatar" width="50">
                <img :src="scope.row.avatar" style="max-width: 120px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="昵称" align="center" prop="nickname" />
          <el-table-column label="手机号" align="center" prop="phone" />
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in userStatusOptions" v-if="scope.row.status==item.dictValue">{{item.dictLabel}}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="收货信息" prop="addressId">
        <el-row>
          <el-col>
            <el-button plain type="primary" icon="el-icon-plus" @click="handleAddUserAddress()">添加收货地址</el-button>
          </el-col>
        </el-row>
        <el-radio-group v-model="form.addressId" style="width:100%">
          <el-table border style="margin-top:5px;" v-loading="addressloading" :data="address">
            <el-table-column label="ID" align="center"  >
              <template slot-scope="scope">
                <el-radio :label="scope.row.addressId"></el-radio>
              </template>
            </el-table-column>
            <el-table-column label="收货人姓名" align="center" prop="realName" />
            <el-table-column label="收货人电话" align="center" prop="phone" />
            <el-table-column label="地址" align="center" prop="detail">
              <template slot-scope="scope">
                {{scope.row.province}} {{scope.row.city}} {{scope.row.district}} {{scope.row.detail}}
              </template>
            </el-table-column>
          </el-table>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="商品列表">
        <el-row>
          <el-col>
            <el-button plain type="primary" icon="el-icon-plus" @click="handleAddProduct">添加商品</el-button>
          </el-col>
        </el-row>
        <el-table border :key="tablekey" width="100%" style="margin-top:5px;" :data="products">
          <el-table-column label="商品名称" align="center" prop="goodsName" />
          <el-table-column label="商品图片" align="center" width="100">
            <template slot-scope="scope">
              <el-popover placement="right" title="" trigger="hover">
                <img slot="reference" :src="scope.row.imgUrl" width="50">
                <img :src="scope.row.imgUrl" style="max-width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="库存" align="center" prop="stock" />
          <el-table-column label="所需积分" align="center" prop="integral" />
          <el-table-column label="需支付金额" align="center" prop="cash" />
          <el-table-column label="商品编号" align="center" prop="barCode" />

          <el-table-column label="操作" align="center" width="100px">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-form-item>
      <el-form-item label="订单备注" prop="mark">
        <el-input type="textarea" rows="2" v-model="form.mark" placeholder="" />
      </el-form-item>
    </el-form>

    <div v-if="formReady" slot="footer" class="dialog-footer" style="float: right; margin-bottom: 20px;">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!-- 对话框部分保持不变 -->
    <el-dialog :title="product.title" v-if="product.open" :visible.sync="product.open" width="1000px" append-to-body>
      <product-select @selectProduct="selectProduct" />
    </el-dialog>
    <el-dialog :title="user.title" v-if="user.open" :visible.sync="user.open" width="500px" append-to-body>
      <add-user @addUser="addUser" />
    </el-dialog>
    <el-dialog :title="userAddress.title" v-if="userAddress.open" :visible.sync="userAddress.open" width="800px" append-to-body>
      <add-user-address ref="addUserAddress" @addUserAddress="addUserAddress" />
    </el-dialog>
    <el-dialog :title="payQr.title" v-if="payQr.open" :visible.sync="payQr.open" width="240px" append-to-body>
      <div style="padding-bottom:15px;">
        <div class="qrcode" ref="qrCodeUrl"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addIntegralOrder } from "@/api/hisStore/integralOrder";
import { getUserList } from "@/api/users/user";
import { getAddressList } from "@/api/users/userAddress";
import { getTcmScheduleList } from "@/api/company/tcmScheduleReport";
import productSelect from "@/views/hisStore/integralOrder/integralProductSelect";
import addUserAddress from "@/views/hisStore/components/addUserAddress";
import config from "@/utils/config";
import QRCode from 'qrcodejs2'
import { treeselect } from "@/api/company/companyDept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: { Treeselect,productSelect,addUserAddress },
  name: "StoreOrder",
  props: {
    customerId: {
      type: Number,
      required: false
    },
    userId: {
      type: Number,
      required: false
    }
  },
  data() {
    return {
      // 添加表单准备状态
      formReady: false,
      createOrderType: null,
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      deliveryPayStatusOptions:[],
      deliveryStatusOptions:[],
      dateRange: [],
      orderTypeOptions:[],
      orderMediumOptions:[],
      payTypeOptions:[],
      payQr:{
        open:false,
        title:"付款二维码"
      },
      user:{
        open:false,
        title:"创建会员"
      },
      userAddress:{
        open:false,
        title:"创建收货地址"
      },
      tablekey:false,
      totalMoney:0.00,
      products:[],
      product:{
        open:false,
        title:"商品选择"
      },
      phone:null,
      address:[],
      addressloading: false,
      userloading: false,
      users:[],
      userStatusOptions:[],
      show:{
        open:false,
        title:"订单详情"
      },
      activeName:"00",
      statusOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      storeOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      createTimeRange:[],
      payTimeRange:[],
      deliveryImportTimeRange:[],
      scheduleOptions:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        extendOrderId: null,
        userId: null,
        realName: null,
        userPhone: null,
        userAddress: null,
        cartId: null,
        freightPrice: null,
        totalNum: null,
        totalPrice: null,
        totalPostage: null,
        payPrice: null,
        payPostage: null,
        deductionPrice: null,
        couponId: null,
        couponPrice: null,
        paid: null,
        payTime: null,
        payType: null,
        status: null,
        refundStatus: null,
        refundReasonWapImg: null,
        refundReasonWapExplain: null,
        refundReasonTime: null,
        refundReasonWap: null,
        refundReason: null,
        refundPrice: null,
        deliverySn: null,
        deliveryName: null,
        deliveryType: null,
        deliveryId: null,
        gainIntegral: null,
        useIntegral: null,
        payIntegral: null,
        backIntegral: null,
        mark: null,
        isDel: null,
        cost: null,
        verifyCode: null,
        storeId: null,
        shippingType: null,
        isChannel: null,
        isRemind: null,
        isSysDel: null
      },
      // 表单参数
      form: {
        addressId:null,
        userId:null,
        products:[],
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "会员信息不能为空", trigger: "submit" }
        ],
        addressId: [
          { required: true, message: "收货信息不能为空", trigger: "submit" }
        ],
        products: [
          { required: true, message: "商品不能为空", trigger: "submit" }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    // 先获取createOrderType，然后再初始化其他数据
    this.initializeForm();
  },
  methods: {
    // 初始化表单的方法
    async initializeForm() {
      try {

        // 2. 然后并行加载其他数据
        await Promise.all([
          this.loadDictionaries(),
          this.loadOtherData(),
          this.initUser()
        ]);

        // 3. 所有数据加载完成后，设置表单为准备状态
        this.formReady = true;

      } catch (error) {
        console.error('Error initializing form:', error);
        this.$message.error('表单初始化失败');
      }
    },

    // 加载字典数据
    async loadDictionaries() {
      const dictPromises = [
        this.getDicts("crm_customer_source").then((response) => {
          this.orderMediumOptions = response.data;
        }),
        this.getDicts("store_order_type").then((response) => {
          this.orderTypeOptions = response.data;
        }),
        this.getDicts("store_pay_type").then((response) => {
          this.payTypeOptions = response.data;
        }),
        this.getDicts("user_status").then((response) => {
          this.userStatusOptions = response.data;
        }),
        this.getDicts("store_order_status").then((response) => {
          this.statusOptions = response.data;
        }),
        this.getDicts("store_order_delivery_status").then((response) => {
          this.deliveryStatusOptions = response.data;
        }),
        this.getDicts("store_delivery_pay_status").then((response) => {
          this.deliveryPayStatusOptions = response.data;
        })
      ];

      await Promise.all(dictPromises);
    },

    // 加载其他数据
    async loadOtherData() {
      await Promise.all([
        this.getTreeselect(),
        getTcmScheduleList().then(response => {
          this.scheduleOptions = response.data;
        })
      ]);
    },

    initUser(){
      return new Promise((resolve) => {
        if(this.userId != null){
          var data={userId:this.userId}
          this.userloading = true;
          this.users=[];
          this.address=[];
          getUserList(data).then(response => {
            this.users = response.data;
            this.userloading = false;
            if(this.users!=null&&this.users.length==1){
              this.form.userId=this.users[0].userId;
              this.getAddressList(this.form.userId).then(() => {
                resolve();
              });
            } else {
              resolve();
            }
          }).catch(() => {
            resolve();
          });
        } else {
          resolve();
        }
      });
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      return treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },

    // 修改getAddressList方法，返回Promise
    getAddressList(userId){
      var data={userId:userId}
      this.addressloading = true;
      this.address=[];
      return getAddressList(data).then(response => {
        this.address = response.data;
        this.addressloading = false;
      });
    },

    // 其他方法保持不变...
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    handleGenPayUrl(row){
      this.payQr.open=true;
      setTimeout(() => {
        var qrcode = new QRCode(this.$refs.qrCodeUrl, {
            text: config.payQRUrl+row.id,
            width: 200,
            height: 200,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
        })
      }, 200);
    },
    handleAddUser(){
      this.user.open=true;
    },
    handleAddUserAddress(){
      this.userAddress.open=true;
      setTimeout(() => {
        this.$refs.addUserAddress.init(this.form.userId);
      }, 500);
    },
    addUserAddress(){
      this.userAddress.open=false;
      //获取地址
      this.getAddressList(this.form.userId);
    },
    addUser(){
      this.user.open=false;
    },
    compute(){
      this.totalMoney=0;
      var that=this;
      this.products.forEach (function (value) {
          that.totalMoney += value.money;
      });
    },
    handleProductCountChange(row){
      this.tablekey = !this.tablekey
      row.money=row.count*row.price;
      this.$forceUpdate();
      this.compute();
    },

    selectProduct(row){
      for(var i=0;i<this.products.length;i++){
        if(this.products[i].id==row.id){
          this.$message.warning("请删除商品在重新选择!")
          return;
        }
      }
      row.count=1;
      row.money=row.count*row.price;
      this.products.push(row);
      this.$message.success("商品"+ row.goodsName + "添加成功")
      this.compute();
      this.product.open=false;
    },
    handleAddProduct(){
      this.product.open=true;
    },
    searchUser(){
      if(this.phone==null||this.phone==""){
        return;
      }
      var data={phone:this.phone}
      this.userloading = true;
      this.users=[];
      this.address=[];
      getUserList(data).then(response => {
        this.users = response.data;
        this.userloading = false;
        if(this.users!=null&&this.users.length==1){
          this.form.userId=this.users[0].userId;
          this.getAddressList(this.form.userId)
        }
      });
    },
    handleDetails(row){
      this.show.open=true;
      const orderId = row.id ;
      setTimeout(() => {
        this.$refs.order.getOrder(orderId);
      }, 500);
    },
    handleClick(tab, event) {
       if(tab.name=="all"){
        this.queryParams.status==null;
      }
      else{
         this.queryParams.status=tab.name;
      }
      this.getList();
    },
    /** 查询订单列表 */
    getList() {
      if(this.queryParams.status=='00'){
        this.queryParams.status=null;
      }
      if(this.createTimeRange!=null&&this.createTimeRange.length==2){
        this.queryParams.createTimeRange=this.createTimeRange[0]+"--"+this.createTimeRange[1]
      }
      else{
        this.queryParams.createTimeRange=null;
      }
      if(this.payTimeRange!=null&&this.payTimeRange.length==2){
        this.queryParams.payTimeRange=this.payTimeRange[0]+"--"+this.payTimeRange[1]
      }
      else{
        this.queryParams.payTimeRange=null;
      }
      if(this.deliveryImportTimeRange!=null&&this.deliveryImportTimeRange.length==2){
        this.queryParams.deliveryImportTimeRange=this.deliveryImportTimeRange[0]+"--"+this.deliveryImportTimeRange[1]
      }
      else{
        this.queryParams.deliveryImportTimeRange=null;
      }
      this.loading = true;

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$emit("closePackage")
    },
    // 表单重置
    reset() {
      this.form = {
        addressId:null,
        userId:null,
        products:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "创建订单";
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if(this.products.length==0){
          this.msgError("请选择商品");
          return;
        }
        this.form.products=this.products;
        if (valid) {
          this.form.goodsId = this.form.products[0].goodsId;
          // console.log("this.form:{}",this.form.products[0].goodsId)
          addIntegralOrder(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("创建成功");
              this.$emit("closePackage")
            }
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
       this.products.splice(this.products.findIndex(item => item.id === row.id), 1)
       this.compute();
    },
  }
};
</script>

<style scoped lang="scss">
.items{
  margin: 5px 0px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  .pic{
    width:60px;
    height:60px;
  }
  .goods-content{
    margin-left: 10px;
    max-width: 200px;
    text-align: left;
    .goods-title{
      overflow:hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow:ellipsis;
    }
  }
}
.el-message-box__message p{
  max-height: 400px;
  overflow:scroll;
}
.import-msg{
  height: 500px;
  overflow: auto;
}
</style>

<style>
.el-descriptions-item__label.is-bordered-label{
  font-weight: normal;
}
</style>
