<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="系统"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in permissionsSysOriginPlatforms"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;">
            <sys-origin-icon :icon="item.value" :desc="item.value"
          /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>
      <div class="filter-item">
        <account-input
          v-model="listQuery.userId"
          :sys-origin="listQuery.sysOrigin"
          placeholder="用户ID"
        />
      </div>
      <el-select
        v-model="listQuery.status"
        placeholder="状态"
        style="width:120px;"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option label="未操作" :value="'NONE'" />
        <el-option label="待审核" :value="'PENDING'" />
        <el-option label="已通过" :value="'PASS'" />
        <el-option label="不通过" :value="'NOT_PASS'" />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="exprotUserBankIdentityInfo"
      >
        导出
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
      @cell-mouse-enter="handleMouseEnter"
    >
      <el-table-column prop="sysOrigin" label="系统" align="center" width="100">
        <template slot-scope="scope">
          <sys-origin-icon
            :icon="scope.row.sysOrigin"
            :desc="scope.row.sysOrigin"
          />
        </template>
      </el-table-column>
      <el-table-column label="用户" align="center" min-width="150">
        <template slot-scope="scope">
          <user-table-exhibit
            :user-profile="scope.row.userProfile"
            :query-details="true"
          />
        </template>
      </el-table-column>
      <el-table-column label="身份图片" align="center" min-width="190">
        <template slot-scope="scope">
          <div v-if="Array.isArray(scope.row.passportFrontUrl)">
            <el-image
              v-for="(url, index) in scope.row.passportFrontUrl"
              :key="index"
              style="width: 50px; height: 50px; margin-right: 5px;"
              :src="url"
              :preview-src-list="scope.row.passportFrontUrl"
              :initial-index="index"
            />
          </div>
          <el-image
            v-else
            style="width: 50px; height: 50px"
            :src="scope.row.passportFrontUrl"
            :preview-src-list="[scope.row.passportFrontUrl]"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="contactNumber"
        label="手机号"
        align="center"
        min-width="100"
      />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.status === 'NONE'">未操作</el-tag>
            <el-tag v-if="scope.row.status === 'PENDING'">待审核</el-tag>
            <el-tag v-if="scope.row.status === 'PASS'">已通过</el-tag>
            <el-tag v-else-if="scope.row.status === 'NOT_PASS'">不通过</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="otherDescription"
        label="描述"
        align="center"
        min-width="200"
      />
      <!-- <el-table-column
        prop="auditDescription"
        label="审核描述"
        align="center"
        min-width="200"
      /> -->
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        width="160"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="修改时间"
        align="center"
        width="160"
      >
        <template slot-scope="scope">
          {{ scope.row.updateTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="100">
        <template slot-scope="scope">
          <!-- <el-button
            type="text"
            :disabled="
              scope.row.status !== 'NONE' && scope.row.status !== 'PENDING'
            "
            @click="auditStatus(scope.row, false)"
            >审核</el-button
          > -->
          <el-button
            type="text"
            :disabled="
              scope.row.status !== 'NONE' && scope.row.status !== 'PENDING'
            "
            @click="auditHandle(scope.row.id, 'PASS')"
            >通过</el-button
          >
          <el-button
            type="text"
            style="color: red;"
            :disabled="
              scope.row.status !== 'NONE' && scope.row.status !== 'PENDING'
            "
            @click="auditHandle(scope.row.id, 'NOT_PASS')"
            >驳回</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <div class="gold-input-box">
      <el-dialog :title="'审核'" :visible="inputBoxVisible" width="400px">
        <el-form
          ref="form"
          :rules="formRules"
          :model="formData"
          label-position="left"
          label-width="80px"
          style="width: 300px; margin-left:50px;"
        >
          <el-form-item label="审核" prop="status">
            <el-select
              v-model.trim="formData.status"
              placeholder="审核"
              clearable
              style="width:100%;"
              class="filter-item"
            >
              <el-option label="审核通过" :value="'PASS'" />
              <el-option label="审核不通过" :value="'NOT_PASS'" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="auditDescription">
            <el-input
              v-model.trim="formData.auditDescription"
              placeholder="请输入备注"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="hideInputBox()">
            取消
          </el-button>
          <el-button
            v-loading="listLoading"
            type="primary"
            @click="auditSubmit()"
          >
            提交
          </el-button>
        </div>
      </el-dialog>
    </div>

    <el-drawer
      title="导出条件"
      :visible="exportConditionVisible"
      :before-close="exportConditionClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div class="exprot-select">
        <div class="drawer-form">
          <el-form
            ref="exportQuery"
            :rules="exportQueryRules"
            :model="exportQuery"
            label-position="left"
            label-width="70px"
          >
            <el-form-item label="系统" prop="sysOrigin">
              <el-select
                v-model="exportQuery.sysOrigin"
                placeholder="系统"
                style="width: 120px"
                class="filter-item"
                @change="handleSearch"
              >
                <el-option
                  v-for="item in permissionsSysOriginPlatforms"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left;">
                    <sys-origin-icon :icon="item.value" :desc="item.value"
                  /></span>
                  <span style="float: left;margin-left:10px">{{
                    item.label
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="exportQuery.status"
                placeholder="状态"
                style="width:120px;"
                class="filter-item"
                clearable
              >
                <el-option label="未操作" :value="'NONE'" />
                <el-option label="待审核" :value="'PENDING'" />
                <el-option label="已通过" :value="'PASS'" />
                <el-option label="不通过" :value="'NOT_PASS'" />
              </el-select>
            </el-form-item>

            <div class="filter-item">
              <el-date-picker
                v-model="rangeDate"
                value-format="timestamp"
                type="datetimerange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </div>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button @click="exportConditionClose()">关闭</el-button>
          <el-button
            type="primary"
            :disabled="exportLoading"
            :loading="exportLoading"
            @click="exportConditionSubmit()"
            >导出</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  getUserBankIdentityInfo,
  auditUserBankIdentityInfo,
  withdrawInfoPass, // 用户认证身份信息审核（通过）
  withdrawInfoNotPass, // 用户认证身份信息审核（驳回）
  exportUserBankIdentityInfo
} from "@/api/app-user";
import Pagination from "@/components/Pagination";
import { pickerOptions } from "@/constant/el-const";
import { mapGetters } from "vuex";

export default {
  name: "UserPropsTable",
  components: { Pagination },
  data() {
    const commonRules = [
      { required: true, message: "必填字段", trigger: "blur" }
    ];

    return {
      runningWaterVisible: false,
      thatRow: null,
      rangeDate: [],
      userInfo: {},
      searchDisabled: false,
      inputBoxVisible: false,
      exportConditionVisible: false,
      thatSelectedUserId: "",
      list: [],
      total: 0,
      exportLoading: false,
      pickerOptions,
      exportQuery: {
        startCreateDate: "",
        endCreateDate: "",
        status,
        sysOrigin: ""
      },
      exportQueryRules: {
        startCreateDate: commonRules,
        endCreateDate: commonRules,
        sysOrigin: commonRules
      },
      listQuery: {
        cursor: 1,
        limit: 20,
        userId: "",
        status: "PENDING",
        sysOrigin: "ATYOU"
      },
      formData: {
        id: "",
        status: "",
        auditDescription: ""
      },
      formRules: {
        status: commonRules
      },
      listLoading: true,
      formEditVisable: false
    };
  },
  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"])
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.exportQuery.startCreateDate = newVal[0];
          this.exportQuery.endCreateDate = newVal[1];
          return;
        }
        this.exportQuery.startCreateDate = "";
        this.exportQuery.endCreateDate = "";
      }
    }
  },
  created() {
    const that = this;
    const querySystem = this.permissionsSysOriginPlatforms[0];
    if (!querySystem) {
      return;
    }
    that.listQuery.sysOrigin = querySystem.value;
    that.renderData();
  },
  methods: {
    renderData(isReset) {
      const that = this;
      if (isReset === true) {
        that.listQuery.cursor = 1;
      }
      that.listLoading = true;
      getUserBankIdentityInfo(that.listQuery)
        .then(res => {
          const { body } = res;
          that.total = body.total || 0;

          that.list = body.records.map(record => {
            try {
              // 假设 passportFrontUrl 是 JSON 字符串，需要解析
              return {
                ...record,
                passportFrontUrl: record.passportFrontUrl
                  ? JSON.parse(record.passportFrontUrl)
                  : null
              };
            } catch (error) {
              // 如果解析失败，保留原值或设置默认值
              console.warn(
                "Failed to parse passportFrontUrl for record:",
                record
              );
              return record;
            }
          });
          that.listLoading = false;
        })
        .catch(er => {
          that.listLoading = false;
        });
    },
    handleSearch() {
      this.renderData(true);
    },
    handleMouseEnter(row) {
      this.thatRow = row;
    },
    formEditSuccess() {
      this.formEditVisable = false;
      this.renderData();
    },
    auditStatus(row, type) {
      const that = this;
      that.formData = {
        id: row.id,
        auditDescription: ""
      };
      that.inputBoxVisible = true;
    },
    hideInputBox() {
      const that = this;
      that.inputBoxVisible = false;
    },
    auditSubmit() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return;
        }
        that.listLoading = true;
        auditUserBankIdentityInfo(that.formData)
          .then(res => {
            that.$message.success("操作成功");
            that.inputBoxVisible = false;
            that.listLoading = false;
            that.renderData();
          })
          .catch(er => {
            that.listLoading = false;
            that.$message.error("操作失败");
            console.error(er);
          });
      });
    },

    // 审核操作
    auditHandle(id, status) {
      const that = this;
      let data = [id];
      that.listLoading = true;
      if (status == "PASS") {
        withdrawInfoPass(data)
          .then(res => {
            that.$message.success("操作成功");
            that.listLoading = false;
            that.renderData();
          })
          .catch(er => {
            that.listLoading = false;
            that.$message.error("操作失败");
            console.error(er);
          });
      } else if (status == "NOT_PASS") {
        withdrawInfoNotPass(data)
          .then(res => {
            that.$message.success("操作成功");
            that.listLoading = false;
            that.renderData();
          })
          .catch(er => {
            that.listLoading = false;
            that.$message.error("操作失败");
            console.error(er);
          });
      }
    },
    exportConditionClose() {
      if (this.exportLoading) {
        this.$message.warning("正在执行导出, 请稍等~");
        return;
      }
      this.exportConditionVisible = false;
    },
    exprotUserBankIdentityInfo() {
      this.exportQuery.sysOrigin = this.listQuery.sysOrigin;
      this.exportConditionVisible = true;
    },
    exportConditionSubmit() {
      const that = this;
      that.$refs.exportQuery.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return false;
        }
        that.exportLoading = true;
        exportUserBankIdentityInfo(
          that.exportQuery,
          "Export UserBankIdentityInfo"
        )
          .then(res => {
            that.exportLoading = false;
            that.exportConditionVisible = false;
          })
          .catch(er => {
            that.exportLoading = false;
            this.$message.error("下载失败！");
          });
      });
    }
  }
};
</script>
