<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-row>
          <el-col>
            <el-input placeholder="请输入会员手机号" style="width:240px;cursor:pointer" v-model="phone">
            </el-input>
            <el-button plain style="margin-left:10px;" @click="searchUser()">查询</el-button>
            <el-button plain style="margin-left:10px;" icon="el-icon-plus" type="primary" @click="handleAddUser()">添加会员</el-button>
          </el-col>
        </el-row>
        <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="barCode" />
          <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.image" width="50">
                <img :src="scope.row.image" style="max-width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" show-overflow-tooltip align="center" prop="productName" />
          <el-table-column label="商品规格" align="center" prop="sku" />
          <el-table-column label="库存" align="center" prop="stock" />
          <el-table-column label="单价" align="center" prop="price" width="200px" v-if="createOrderType == 1">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.price" @change="handleProductCountChange(scope.row)" size="mini" :min="0.01"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="price" v-if="createOrderType == 2"/>
          <el-table-column label="数量" align="center" prop="count" width="200px" :key="tablekey">
            <template slot-scope="scope">
              <div>
                <el-input-number v-model="scope.row.count" @change="handleProductCountChange(scope.row)" size="mini" :min="1" :max="scope.row.stock"></el-input-number>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="小计" align="center" prop="money" />
          <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-row>
          <el-col>
            <span>商品合计:{{products.length}}</span><span style="margin-left:10px;">商品总价:{{totalMoney.toFixed(2)}}</span>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="form.orderType" placeholder="请选择订单类型" clearable size="small">
          <el-option v-for="item in orderTypeOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
      </el-form-item>

      <el-form-item label="媒体来源" prop="orderMedium" v-if="orderMediumOptions.length>0">
        <el-select v-model="form.orderMedium" placeholder="请选择媒体来源" clearable size="small">
          <el-option v-for="item in orderMediumOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
      </el-form-item>

      <el-form-item label="支付方式" prop="payType">
        <el-select v-model="form.payType" placeholder="请选择支付方式" clearable size="small">
          <el-option v-for="item in payTypeOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
      </el-form-item>

      <el-form-item label="改价" prop="payPrice" v-if="createOrderType == 2">
        <el-input-number v-model="form.payPrice" placeholder="修改商品总价" size="medium" :precision="2" :min="0.01" :step="0.1" />
      </el-form-item>

      <el-form-item label="物流代收" prop="amount" v-if="form.payType == '3'">
        <el-input-number v-model="form.amount" placeholder="平台支付价格" size="medium" :precision="2" :min="0.01" :step="0.1" />
      </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 {exportStoreOrderItems, createUserOrder,listStoreOrder, getStoreOrder, delStoreOrder, addStoreOrder, updateStoreOrder, exportStoreOrder,getCreateOrderType } from "@/api/hisStore/storeOrder";
import { getUserList } from "@/api/users/user";
import { getAddressList } from "@/api/users/userAddress";
import { getTcmScheduleList } from "@/api/company/tcmScheduleReport";
import productOrder from "@/views/hisStore/components/productOrder";
import productSelect from "@/views/hisStore/components/productSelect";
import addUser from "@/views/hisStore/components/addUser";
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,productOrder,productSelect,addUser,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 {
        // 1. 首先获取createOrderType
        const response = await getCreateOrderType();
        this.createOrderType = response.createSalesOrderType;

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

        // 3. 所有数据加载完成后，设置表单为准备状态
        this.formReady = true;
        console.log('Form is ready to display');

      } 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(){
      if(this.form.userId==null){
        this.msgError("请选择会员");
        return;
      }
      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){
          return;
        }
      }
      row.count=1;
      row.money=row.count*row.price;
      this.products.push(row);
      this.$message.success("商品"+ row.productName + "添加成功")
      this.compute();
    },
    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;
      listStoreOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.storeOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    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 = "创建订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStoreOrder(id).then(response => {
        this.form = response.data;
        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.customerId = this.customerId;
          createUserOrder(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();
    },
    /** 导出按钮操作 */
    handleExport() {
      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;
      }
      const queryParams = this.addDateRange(this.queryParams, this.dateRange);
      this.$confirm('是否确认导出所有订单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStoreOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handleExportItems() {
      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;
      }
      const queryParams = this.addDateRange(this.queryParams, this.dateRange);
      this.$confirm('是否确认导出所有订单明细数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStoreOrderItems(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</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>
