<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">



      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工号" prop="jobNumber">
        <el-input
          v-model="queryParams.jobNumber"
          placeholder="请输入工号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.users_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="等级" prop="level">
        <el-input
          v-model="queryParams.level"
          placeholder="请输入工号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用状态" prop="loginStatus">
        <el-select v-model="queryParams.loginStatus" placeholder="请选择使用状态" clearable>
          <el-option
            v-for="dict in dict.type.users_login_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="当前佣金" prop="priceRange"  label-width="auto">
        <el-input
          v-model="queryParams.commissionMin"
          placeholder="最低价"
          style="width: 100px; margin-right: 10px;"
          type="number"
          min="0"
          clearable
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.commissionMax"
          placeholder="最高价"
          style="width: 100px;"
          type="number"
          min="0"
          clearable
        />
      </el-form-item>


      <el-form-item label="质保金" prop="priceRange"  label-width="auto">
        <el-input
          v-model="queryParams.marginMin"
          placeholder="最低价"
          style="width: 100px; margin-right: 10px;"
          type="number"
          min="0"
          clearable
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.marginMax"
          placeholder="最高价"
          style="width: 100px;"
          type="number"
          min="0"
          clearable
        />
      </el-form-item>


      <el-form-item label="累计提现" prop="priceRange"  label-width="auto">
        <el-input
          v-model="queryParams.totalCommMin"
          placeholder="最低价"
          style="width: 100px; margin-right: 10px;"
          type="number"
          min="0"
          clearable
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.totalCommMax"
          placeholder="最高价"
          style="width: 100px;"
          type="number"
          min="0"
          clearable
        />
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:users:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:users:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:users:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="usersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" width="55"  prop="id" />
      <el-table-column label="工号" align="center" prop="jobNumber" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="openid" align="center" prop="openid" />
      <el-table-column label="头像" align="center" prop="avatar" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" align="center" prop="loginStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.users_login_status" :value="scope.row.loginStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="状态"  width="85"  align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="本月累计单量" align="center" prop="toa" />
      <el-table-column label="签到时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.workerTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="等级" align="center" prop="level">
        <template slot-scope="scope">
          <el-select v-model="scope.row.level"  @change="handleRowClick(scope.row)">
            <el-option
              v-for="item in levelList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
<!--          <el-link type="primary" @click="showWorkerLevelDialog(scope.row)">{{ scope.row.level }}</el-link>-->
        </template>
      </el-table-column>
      <el-table-column label="当前佣金" align="center" prop="commission" />
      <el-table-column label="累计佣金" align="center" prop="totalComm">
        <template slot-scope="scope">
          <el-link
            type="primary"
            @click="showWorkerMoneyLog(scope.row)"
            v-hasPermi="['system:workerMoneyLog:list']"
          >{{ scope.row.totalComm }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="质保金" align="center" prop="margin">
        <template slot-scope="scope">
          <el-link
            type="primary"
            @click="showWorkerMarginLog(scope.row)"
            v-hasPermi="['system:WorkerMarginLog:list']"
          >{{ scope.row.margin }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="累计提现" align="center" prop="propose" />
      <el-table-column label="服务区域" align="center" prop="serviceCityIds" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.serviceCityIds">{{ formatServiceAreas(scope.row.serviceCityIds) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="技能" align="center" prop="skillIds" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.skillIds">{{ formatSkillNames(scope.row.skillIds) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:users:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:users:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <UserEditDialog
      :visible.sync="editDialogVisible"
      :user="editUser"
      :mode="editMode"
      @confirm="handleEditConfirm"
      @cancel="editDialogVisible = false"
    />

    <!-- 师傅佣金明细弹窗 -->
    <el-dialog :title="'师傅佣金明细'" :visible.sync="workerMoneyLogDialogVisible" width="70%" top="5vh" append-to-body>
      <worker-money-log-table
        :worker-id="currentWorkerId"
        @close="workerMoneyLogDialogVisible = false"
        v-if="workerMoneyLogDialogVisible"
      />
    </el-dialog>

        <!-- 师傅质保金明细弹窗 -->
    <el-dialog :title="'师傅质保金明细'" :visible.sync="workerMarginLogDialogVisible" width="70%" top="5vh" append-to-body>
      <worker-margin-log-detail-table 
        :worker-id="currentWorkerId" 
        @close="workerMarginLogDialogVisible = false" 
        @margin-changed="handleMarginChanged"
        v-if="workerMarginLogDialogVisible"
        :key="'margin-log-' + currentWorkerId"
      />
    </el-dialog>

    <WorkerLevelSelectDialog
      :visible.sync="workerLevelDialogVisible"
      :user-id="workerLevelUserId"
      :user-name="workerLevelUserName"
      @level-selected="handleWorkerLevelSelected"
    />
  </div>
</template>

<script>
import { listUsers, getUsers, delUsers, addUsers, updateUsers,getUserDataList,changetypeStatus } from "@/api/system/users"
import { listWorkerLevel } from '@/api/system/WorkerLevel'
import { selectAreaList } from "@/api/system/WorkerApply"
import { getSiteSkillList } from "@/api/system/SiteSkill"
import UserEditDialog from './UserEditDialog.vue'
import WorkerMoneyLogTable from '@/views/system/workerMoneyLog/WorkerMoneyLogTable.vue'
import WorkerMarginLogDetailTable from '@/views/system/WorkerMarginLog/WorkerMarginLogTable.vue'
import WorkerLevelSelectDialog from '../workerLevelSelect/WorkerLevelSelectDialog.vue'


export default {
  name: "Users",
  dicts: ['users_status','users_login_status'],
  components: { UserEditDialog, WorkerMoneyLogTable, WorkerMarginLogDetailTable, WorkerLevelSelectDialog },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      levelList: [],

      userDataList: [],
      // 用户列表表格数据
      usersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        totalCommMin: null,
        totalCommMax: null,
        marginMin: null,
        marginMax: null,
        commissionMin: null,
        commissionMax: null,
        jobNumber: null,
        type: '2',
        name: null,
        phone: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "昵称不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "电话不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "1:启用  0：关闭不能为空", trigger: "change" }
        ],
      },
      editDialogVisible: false,
      editUser: {},
      editMode: 'add',
      workerMoneyLogDialogVisible: false,
      currentWorkerId: null,
      workerMarginLogDialogVisible: false,
      workerLevelDialogVisible: false,
      workerLevelUserId: null,
      workerLevelUserName: '',
      // 地区数据缓存
      areaDataCache: {},
      // 技能数据缓存
      skillDataCache: {}
    }
  },
  created() {
    this.getList()
    this.getlevelList();
    this.initAreaDataCache();
    this.initSkillDataCache();

  },
  mounted() {
    // 确保在组件挂载后重新获取数据，以便格式化方法能正常工作
    this.$nextTick(() => {
      this.getList();
    });
  },
  methods: {
    /** 查询用户列表列表 */
    getList() {
      this.loading = true
      listUsers(this.queryParams).then(response => {
        this.usersList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        nickname: null,
        phone: null,
        password: null,
        rememberToken: null,
        openid: null,
        avatar: null,
        type: null,
        workerTime: null,
        integral: null,
        totalIntegral: null,
        status: null,
        level: null,
        commission: null,
        totalComm: null,
        margin: null,
        jobNumber: null,
        prohibitTime: null,
        prohibitTimeNum: null,
        toa: null,
        serviceCityPid: null,
        serviceCityIds: null,
        skillIds: null,
        propose: null,
        loginStatus: null,
        isStop: null,
        middleAuth: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    getlevelList(){
      listWorkerLevel().then(response => {
        this.levelList = response.rows
      })
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleRowClick(row) {

      updateUsers(row).then(() => {
        this.$message.success('修改成功')

      })
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.editUser = {
        name: undefined,
        phone: undefined,
        avatar: undefined,
        prohibitTime: undefined,
        prohibitTimeNum: 0,
        serviceCityPid: undefined,
        serviceCityIds: undefined,
        skillIds: undefined,
        commission: undefined,
        status: 1
      };
      this.editMode = 'add';
      this.editDialogVisible = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      getUsers(id).then(response => {
        this.editUser = response.data;
        this.editMode = 'edit';
        this.editDialogVisible = true;
      })
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用"
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"状态吗？').then(function() {
        return changetypeStatus(row.id, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUsers(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addUsers(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除用户列表编号为"' + ids + '"的数据项？').then(function() {
        return delUsers(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/users/export', {
        ...this.queryParams
      }, `users_${new Date().getTime()}.xlsx`)
    },
    handleEditConfirm(user) {
      if (this.editMode === 'add') {
        addUsers(user).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.editDialogVisible = false;
          this.getList();
        });
      } else {
        updateUsers(user).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.editDialogVisible = false;
          this.getList();
        });
      }
    },
    showWorkerMoneyLog(row) {
      console.log('点击查看师傅佣金明细，师傅信息:', row);
      if (!row || !row.id) {
        this.$message.error('师傅信息不完整，无法查看佣金明细');
        return;
      }
      this.currentWorkerId = row.id;
      this.workerMoneyLogDialogVisible = true;
      console.log('设置currentWorkerId:', this.currentWorkerId);
    },
    showWorkerMarginLog(row) {
      console.log('点击查看师傅质保金明细，师傅信息:', row);
      if (!row || !row.id) {
        this.$message.error('师傅信息不完整，无法查看质保金明细');
        return;
      }
      this.currentWorkerId = row.id;
      this.workerMarginLogDialogVisible = true;
    },
    showWorkerLevelDialog(row) {
      this.workerLevelUserId = row.id;
      this.workerLevelUserName = row.name;
      this.workerLevelDialogVisible = true;
    },
    handleWorkerLevelSelected() {
      this.workerLevelDialogVisible = false;
      this.getList(); // 选中后刷新列表
    },
    // 处理质保金变动事件
    handleMarginChanged() {
      console.log('质保金发生变动，刷新师傅列表');
      this.getList(); // 刷新师傅列表，更新质保金显示
    },
    // 格式化服务区域显示
    formatServiceAreas(serviceCityIds) {
      if (!serviceCityIds) return '-';
      try {
        console.log('格式化服务区域，原始数据:', serviceCityIds, '类型:', typeof serviceCityIds);
        
        // 如果是字符串，先转换为数组
        let areaIds = [];
        if (typeof serviceCityIds === 'string') {
          // 处理可能是JSON字符串的情况
          if (serviceCityIds.startsWith('[') && serviceCityIds.endsWith(']')) {
            try {
              areaIds = JSON.parse(serviceCityIds);
            } catch (e) {
              areaIds = serviceCityIds.split(',').map(id => id.trim()).filter(id => id);
            }
          } else {
            areaIds = serviceCityIds.split(',').map(id => id.trim()).filter(id => id);
          }
        } else if (Array.isArray(serviceCityIds)) {
          areaIds = serviceCityIds;
        }
        
        console.log('解析后的地区ID数组:', areaIds);
        console.log('地区数据缓存:', this.areaDataCache);
        
        if (areaIds.length === 0) return '-';
        
        // 从缓存中获取地区名称
        const areaNames = areaIds.map(id => {
          const cached = this.areaDataCache[id];
          console.log(`地区ID ${id} 对应的缓存数据:`, cached);
          return cached ? cached.title : id;
        });
        
        const result = areaNames.join(', ');
        console.log('格式化结果:', result);
        return result;
      } catch (error) {
        console.error('格式化服务区域失败:', error);
        return serviceCityIds;
      }
    },
    // 格式化技能名称显示
    formatSkillNames(skillIds) {
      if (!skillIds) return '-';
      try {
        console.log('格式化技能名称，原始数据:', skillIds, '类型:', typeof skillIds);
        
        // 如果是字符串，先转换为数组
        let skillIdArray = [];
        if (typeof skillIds === 'string') {
          // 处理可能是JSON字符串的情况
          if (skillIds.startsWith('[') && skillIds.endsWith(']')) {
            try {
              skillIdArray = JSON.parse(skillIds);
            } catch (e) {
              skillIdArray = skillIds.split(',').map(id => id.trim()).filter(id => id);
            }
          } else {
            skillIdArray = skillIds.split(',').map(id => id.trim()).filter(id => id);
          }
        } else if (Array.isArray(skillIds)) {
          skillIdArray = skillIds;
        }
        
        console.log('解析后的技能ID数组:', skillIdArray);
        console.log('技能数据缓存:', this.skillDataCache);
        
        if (skillIdArray.length === 0) return '-';
        
        // 从缓存中获取技能名称
        const skillNames = skillIdArray.map(id => {
          const cached = this.skillDataCache[id];
          console.log(`技能ID ${id} 对应的缓存数据:`, cached);
          return cached ? cached.title : id;
        });
        
        const result = skillNames.join(', ');
        console.log('格式化结果:', result);
        return result;
      } catch (error) {
        console.error('格式化技能名称失败:', error);
        return skillIds;
      }
    },
    // 初始化地区数据缓存
    initAreaDataCache() {
      console.log('开始初始化地区数据缓存');
      // 获取所有省份数据
      selectAreaList("100000").then(response => {
        console.log('获取省份数据成功:', response);
        if (response.data) {
          response.data.forEach(province => {
            this.areaDataCache[province.id] = province;
            console.log(`添加省份到缓存: ${province.id} -> ${province.title}`);
            // 获取该省份下的城市数据
            selectAreaList(province.id).then(cityResponse => {
              console.log(`获取城市数据成功 (${province.id}):`, cityResponse);
              if (cityResponse.data) {
                cityResponse.data.forEach(city => {
                  this.areaDataCache[city.id] = city;
                  console.log(`添加城市到缓存: ${city.id} -> ${city.title}`);
                });
              }
            }).catch((error) => {
              console.error(`获取城市数据失败 (${province.id}):`, error);
              // 如果获取城市数据失败，使用默认数据
              if (province.id === "610100") {
                const defaultCities = [
                  { id: "610102", title: "新城区" },
                  { id: "610103", title: "碑林区" },
                  { id: "610104", title: "莲湖区" },
                  { id: "610111", title: "灞桥区" },
                  { id: "610112", title: "未央区" },
                  { id: "610113", title: "雁塔区" },
                  { id: "610114", title: "阎良区" },
                  { id: "610115", title: "临潼区" },
                  { id: "610116", title: "长安区" },
                  { id: "610117", title: "高陵区" }
                ];
                defaultCities.forEach(city => {
                  this.areaDataCache[city.id] = city;
                  console.log(`添加默认城市到缓存: ${city.id} -> ${city.title}`);
                });
              }
            });
          });
        }
      }).catch((error) => {
        console.error('获取省份数据失败:', error);
        // 如果获取省份数据失败，使用默认数据
        const defaultProvinces = [
          { id: "610100", title: "西安市" },
          { id: "610200", title: "铜川市" },
          { id: "610300", title: "宝鸡市" }
        ];
        defaultProvinces.forEach(province => {
          this.areaDataCache[province.id] = province;
          console.log(`添加默认省份到缓存: ${province.id} -> ${province.title}`);
        });
      });
    },
    // 初始化技能数据缓存
    initSkillDataCache() {
      console.log('开始初始化技能数据缓存');
      getSiteSkillList().then(response => {
        console.log('获取技能数据成功:', response);
        if (response.code === 200 && response.data) {
          response.data.forEach(skill => {
            this.skillDataCache[skill.id] = skill;
            console.log(`添加技能到缓存: ${skill.id} -> ${skill.title}`);
          });
        }
      }).catch((error) => {
        console.error('获取技能数据失败:', error);
        // 如果获取技能数据失败，使用默认数据
        const defaultSkills = [
          { id: 1, title: '水电工' },
          { id: 2, title: '油工师傅' },
          { id: 3, title: '改造维修' },
          { id: 4, title: '工程施工' }
        ];
        defaultSkills.forEach(skill => {
          this.skillDataCache[skill.id] = skill;
          console.log(`添加默认技能到缓存: ${skill.id} -> ${skill.title}`);
        });
      });
    }
  }
}
</script>
