<template>
  <div style="background-color: #f0f2f5; padding-bottom: 20px; min-height: 100%; " >
    <div class="contentx" v-if="item!=null" >
      <div class="desct">
        基本信息
      </div>
      <el-descriptions title="" :column="3" border>

        <el-descriptions-item label="会员id" >
          <span v-if="item!=null">{{item.userId}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="用户昵称" >
          <span v-if="item!=null">{{item.nickName}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="用户头像" >
          <el-image v-if="item.avatar!=null"
                    style="width: 50px;"
                    :src="item.avatar">
          </el-image>
        </el-descriptions-item>
        <el-descriptions-item label="手机号码" >
          <template v-if="item!=null">
            <span v-if="item.phone" style="margin-right: 8px;">{{item.phone}}</span>
            <el-button
                type="primary"
                size="mini"
                v-hasPermi="['his:user:bindPhNum']"
                @click="openBindPhone"
            >{{ item.phone ? '修改手机号' : '绑定手机号' }}</el-button>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="用户积分" >
          <span v-if="item!=null">{{item.integral}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="状态" >
                 <span v-if="item!=null">
                       <dict-tag :options="userOptions" :value="item.status"/>
                 </span>
        </el-descriptions-item>

        <el-descriptions-item label="上级昵称" >
          <span v-if="item!=null">{{item.tuiName}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="上级手机号码" >
          <span v-if="item!=null">{{item.tuiPhone}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="推广员关联时间" >
          <span v-if="item!=null">{{item.tuiTime}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="下级人数" >
          <span v-if="item!=null">{{item.tuiUserCount}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="最后一次登录ip" >
          <span v-if="item!=null">{{item.lastIp}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="余额" >
          <span v-if="item!=null">{{item.balance}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" >
          <span v-if="item!=null">{{item.createTime}}</span>
        </el-descriptions-item>

        <el-descriptions-item label="更新时间" >
          <span v-if="item!=null">{{item.updateTime}}</span>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <!-- 积分记录 -->
    <div class="contentx" v-if="item!=null" >
      <div class="desct" style="display: flex; justify-content: space-between; align-items: center;">
        <span>用户积分记录</span>
        <el-button type="primary" @click="handleIntegralPurchase">积分购</el-button>
      </div>
      <userIntegralDetails  ref="userIntegralDetail" />
    </div>

    <div class="contentx" v-if="item!=null">
      <div class="desct"> 优惠劵领取信息</div>
      <el-tabs type="card" v-model="actName" @tab-click="handleClickX">
        <el-tab-pane label="全部" name="10"></el-tab-pane>
        <el-tab-pane v-for="(item,index) in couponStatusOptions" :label="item.dictLabel" :name="item.dictValue"></el-tab-pane>
      </el-tabs>
      <el-table v-loading="loading" :data="userCouponList">
        <el-table-column label="优惠劵标题" align="center" prop="title" />
        <el-table-column label="券号" align="center" prop="couponCode" />
        <el-table-column label="会员昵称" align="center" prop="nickName" />
        <el-table-column label="会员电话" align="center" prop="phone" />
        <el-table-column label="关联订单ID" align="center" prop="businessId" />
        <el-table-column label="订单类型" align="center" prop="businessType">
          <template slot-scope="scope">
            <dict-tag :options="businessTypeOptions" :value="scope.row.businessType"/>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="couponStatusOptions" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="领取时间" align="center" prop="createTime" width="180"/>
        <el-table-column label="使用时间" align="center" prop="useTime" width="180"/>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <div class="contentx" v-if="item!=null && fsUserInfo !== 'gzzdy'">
      <div class="desct">
              <span v-if="patientInfo">
                {{ patientInfo }}
              </span>
        <span v-else>
                患者信息
              </span>
      </div>
      <userPatietDetails  ref="userPatietDetail" />

    </div>

    <div class="contentx" v-if="item!=null" >
      <div class="desct">
        用户地址
      </div>
      <userAddDetails  ref="userAddDetail" />

    </div>
    <div class="contentx" v-if="item!=null && fsUserInfo !== 'gzzdy'" >
      <div class="desct">
        用户药品订单
      </div>
      <userStorerDetails  ref="userDetails" />
    </div>
    <div class="contentx" v-if="item!=null && fsUserInfo !== 'gzzdy'" >
      <div class="desct">
        用户问诊订单
      </div>
      <userInquiryOrderDetails  ref="InquiryDetails" />
    </div>

    <div class="contentx" v-if="item != null && fsUserInfo === 'gzzdy' || fsUserInfo === 'hcl'" >
      <div class="desct">
        商城订单
      </div>
      <userStoreOrderList  ref="userStoreOrderList" />
    </div>

    <!-- 回访记录 -->
    <customerVisitSection ref="customerVisitSection" />

    <!-- 积分购弹窗 -->
    <el-dialog
      title="积分购"
      :visible.sync="integralPurchaseVisible"
      width="60%"
      append-to-body
    >
      <!-- 积分购弹窗 -->
      <add-order-dialog
        :key="currentUserId + '-' + refreshKey"
        :userId="currentUserId"
        @closePackage="integralPurchaseVisible = false"
      />


    </el-dialog>

    <!-- 绑定手机号弹窗 -->
    <el-dialog
      :title="item && item.phone ? '修改手机号' : '绑定手机号'"
      :visible.sync="bindPhoneVisible"
      width="420px"
      append-to-body
      @close="resetBindPhoneForm"
    >
      <el-form ref="bindPhoneForm" :model="bindPhoneForm" :rules="bindPhoneRules" label-width="90px">
        <el-form-item label="手机号码" prop="phNum">
          <el-input v-model="bindPhoneForm.phNum" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bindPhoneVisible = false">取 消</el-button>
        <el-button type="primary" :loading="bindPhoneLoading" @click="submitBindPhone">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPatient, getPatient, delPatient, addPatient, updatePatient, exportPatient ,getPatientByUserId} from "@/api/store/patient";
import { listUser, getUser, delUser, addUser, updateUser, exportUser ,getUserAddr, bindPhNum} from "@/api/store/user";
import { getListUserCoupon } from "@/api/store/userCoupon";
import userStorerDetails from "../components/userStorerDetails.vue";
import userPatietDetails from "../components/userPatietDetails.vue";
import userInquiryOrderDetails from "../components/userInquiryOrderDetails.vue";
import userAddDetails from "../components/userAddDetails.vue";
import userIntegralDetails from "../components/userIntegralDetails.vue";
import AddOrderDialog from "../../hisStore/integralOrder/addOrder.vue"; // 导入积分购组件
import userStoreOrderList from "../components/userStoreOrderList.vue"; //商城订单
import customerVisitSection from "../components/customerVisitSection.vue"; //回访记录

export default {
  name: "storedet",
  props:["data"],
  components: {
    userStorerDetails,
    userInquiryOrderDetails,
    userPatietDetails,
    userAddDetails,
    userIntegralDetails,
    AddOrderDialog, // 注册积分购组件
    userStoreOrderList,
    customerVisitSection
  },
  data() {
    return {
      refreshKey: 0, // 每次点击刷新用
      patientInfo: process.env.VUE_APP_PATIENT_INFO,
      addr:[],
      patient:[],
      userOptions: [],
      statusOptions: [],
      sexOptions: [],
      pOptions: [],
      item:null,
      total: 0,
      loading: true,
      // 积分购相关
      integralPurchaseVisible: false,
      currentUserId: null,
      // 绑定手机号
      bindPhoneVisible: false,
      bindPhoneLoading: false,
      bindPhoneForm: {
        phNum: ''
      },
      bindPhoneRules: {
        phNum: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      // 会员优惠券表格数据
      userCouponList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        couponId: null,
      },
      actName:"10",
      businessTypeOptions:[],
      couponStatusOptions:[],
      fsUserInfo: process.env.VUE_APP_FS_USER_INFO
    }
  },
  created() {
    this.getDicts("sys_user_status").then(response => {
      this.userOptions = response.data;
    });
    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_patient_status").then(response => {
      this.pOptions = response.data;
    });
    this.getDicts("sys_patient_sex").then(response => {
      this.sexOptions = response.data;
    });
    this.getDicts("sys_coupon_business_type").then(response => {
      this.businessTypeOptions = response.data;
    });

    this.getDicts("sys_coupon_status").then(response => {
      this.couponStatusOptions = response.data;
    });
  },
  methods: {
    // 积分购相关方法
    handleIntegralPurchase() {
      if (this.item && this.item.userId) {
        this.currentUserId = this.item.userId;
        this.refreshKey++; // 每次点击都强制刷新
        this.integralPurchaseVisible = true;
      } else {
        this.$message.warning('无法获取用户信息');
      }
    },

    handleCloseIntegralPurchase() {
      this.integralPurchaseVisible = false;
      this.currentUserId = null;
    },

    openBindPhone() {
      this.resetBindPhoneForm();
      this.bindPhoneVisible = true;
    },

    resetBindPhoneForm() {
      this.bindPhoneForm = { phNum: '' };
      this.bindPhoneLoading = false;
      if (this.$refs.bindPhoneForm) {
        this.$refs.bindPhoneForm.clearValidate();
      }
    },

    submitBindPhone() {
      this.$refs.bindPhoneForm.validate(valid => {
        if (!valid) return;
        if (!this.item || !this.item.userId) {
          this.$message.warning('无法获取会员信息');
          return;
        }
        this.bindPhoneLoading = true;
        bindPhNum({
          phNum: Number(this.bindPhoneForm.phNum),
          fsUserId: this.item.userId
        }).then(res => {
          if (res.code === 200) {
            this.msgSuccess(res.msg || '操作成功');
            this.bindPhoneVisible = false;
            this.item.phone = this.bindPhoneForm.phNum;
            this.getDetails(this.item.userId);
          } else {
            this.msgError(res.msg || '操作失败');
          }
        }).catch(() => {
          // 错误信息由请求拦截器处理
        }).finally(() => {
          this.bindPhoneLoading = false;
        });
      });
    },

    handleClickX(tab, event) {
      if(tab.name=="10"){
        this.queryParams.status=null;
      }else{
        this.queryParams.status=tab.name;
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },

    getList() {
      this.loading = true;
      getListUserCoupon(this.queryParams).then(response => {
        this.userCouponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getDetails(orderId) {
      this.item=null;
      getUser(orderId).then(response => {
        this.item = response.data;
        setTimeout(() => {
          this.$refs.userDetails.getUserDetails(orderId);
        }, 1);
        setTimeout(() => {
          this.$refs.InquiryDetails.getInquiryDetails(orderId,1);
        }, 1);
        setTimeout(() => {
          this.$refs.userPatietDetail.getPatList(orderId);
        }, 1);
        setTimeout(() => {
          this.$refs.userAddDetail.getAddList(orderId);
        }, 1);
        setTimeout(() => {
          this.$refs.userIntegralDetail.getIntegralLogs(orderId);
        }, 1);
        setTimeout(() => {
          if (this.$refs.userStoreOrderList) {
            this.$refs.userStoreOrderList.getUserOrderDetails(orderId);
          }
        }, 1);
        setTimeout(() => {
          if (this.$refs.customerVisitSection) {
            this.$refs.customerVisitSection.init(orderId);
          }
        }, 1);
      });

      this.patient=null;
      getPatientByUserId(orderId).then(response => {
        this.patient = response.data;
      });

      getUserAddr(orderId).then(response => {
        this.addr = response.data;
      });

      this.queryParams.userId=orderId;
      this.getList();
    },
  }
}
</script>

<style>
.contentx{
  height: 100%;
  background-color: #fff;
  padding: 0px 20px 20px;
  margin: 20px;
}
.el-descriptions-item__label.is-bordered-label{
  font-weight: normal;
}
.el-descriptions-item__content {
  max-width: 150px;
  min-width: 100px;
}
.desct{
  padding-top: 20px;
  padding-bottom: 20px;
  color: #524b4a;
  font-weight: bold;
}
</style>
