<template>
  <div
    id="user_Role"
    v-loading="pictLoading"
    class="view"
    element-loading-background="rgba(43, 48, 67, 0.65)"
    element-loading-spinner="el-icon-loading"
  >
    <div class="crm_search">
      <el-form ref="formRef" :model="search" label-width="">
        <el-row>
          <el-col :span="24" :md="24" :lg="24">
            <el-form-item>
              <el-date-picker
                v-model="search.date"
                class="crm_date_pick crm-border-radius-no"
                type="daterange"
                unlink-panels
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                range-separator="-"
                :start-placeholder="$t('Placeholder.Start')"
                :end-placeholder="$t('Placeholder.End')"
                @change="dateChange"
              >
              </el-date-picker>
              <el-button
                class="crm-border-radius-no crm-border-left-no"
                :icon="Search"
                @click="toSearch"
              ></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="display['R-Role-Add'].show">
          <div class="search_action_btn">
            <span class="crm-cursor" @click="addRole">
              <el-icon><Plus /></el-icon>
              <span>{{ $t('Btn.Add') }}</span>
            </span>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="mock_tableData" stripe style="width: 100%">
      <el-table-column prop="" align="left" :label="$t('Label.RoleName')">
        <template #default="scope">
          {{ scope.row.name || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="" align="left" :label="$t('Label.RoleGroup')">
        <template #default="scope">
          <span>{{
            scope.row.departmentId ? $t(departmentNames[scope.row.departmentId]) : '--'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="merchantName" align="left" :label="$t('Label.ShopName')">
        <template #default="scope">
          <span>{{ scope.row.merchantName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="" align="left" :label="$t('Label.Date')">
        <template #default="scope">
          {{ scope.row.addTime || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="" align="center" :label="$t('Label.Action')">
        <template #default="scope">
          <el-dropdown v-if="user.roleId !== scope.row.id" trigger="click" @command="handleCommand">
            <span class="el-dropdown-link crm-cursor">
              <i style="font-weight: bold; font-size: 20px" class="iconfont iconcaidan"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-if="display['R-Role-Update'].show"
                  :command="{ type: 'editor', row: scope.row }"
                >
                  <el-icon><Edit /></el-icon>
                  <span>{{ $t('Btn.Editor') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-Role-Delete'].show"
                  :command="{ type: 'delete', id: scope.row.id }"
                >
                  <el-icon><Delete /></el-icon>
                  <span>{{ $t('Btn.Delete') }}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="pagerInfo.rowTotal" class="crm_pagination">
      <div class="crm_page_total">
        <span>{{ $t('Page.total.item1') }}</span>
        <span>{{ pagerInfo.rowTotal }}</span>
        <span>{{ $t('Page.total.item2') }}</span>
      </div>
      <el-pagination
        class="page"
        background
        layout="sizes, prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagerInfo.row"
        :total="pagerInfo.rowTotal"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>

    <!-- 账户新增/修改弹出 -->
    <RoleAdd
      :dialog-info-trading-add="dialogInfoTradingAdd"
      :editor="editor"
      :form-list="formList"
      @confirm-to-reload="confirmToReload"
      @close-add="closeAdd"
    >
    </RoleAdd>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted, inject } from 'vue'
  import { Search, Edit, Delete, Plus } from '@element-plus/icons-vue'
  import { ElMessageBox } from 'element-plus'
  import Service from '@/service/user'
  import Config from '@/config/index'
  import RoleAdd from './components/RoleAdd'
  import { departmentNames } from '@/views/user/userRole/const'
  import { useI18n } from 'vue-i18n'
  import { safeGetUser } from '@/utils/safeJson'

  const { Code } = Config
  const { t } = useI18n()
  const Session = inject('session')
  const pigeon = inject('pigeon')

  // ref 响应式数据
  const pictLoading = ref(false)
  const mock_tableData = ref([])
  const dialogInfoTradingAdd = ref(false)
  const editor = ref(null)
  const addType = ref('')
  const formRef = ref(null)

  // reactive 响应式对象
  const search = reactive({
    date: [],
    startDate: '',
    endDate: '',
  })

  const formList = reactive({})

  const pagerInfo = reactive({
    row: 10,
    current: 1,
    pageTotal: 0,
    rowTotal: 0,
  })

  // computed 计算属性
  const display = computed(() => {
    const displayData = Session.Get('display', true)
    return displayData ? JSON.parse(displayData) : {}
  })
  const user = computed(() => {
    return safeGetUser(Session)
  })

  // 方法
  const handleCommand = (command) => {
    if (command.type == 'editor') {
      Object.assign(formList, {
        id: command.row.id,
        name: command.row.name,
        departmentId: command.row.departmentId,
        merchantId: command.row.merchantId,
      })
      addType.value = 'user_Role'
      dialogInfoTradingAdd.value = true
      editor.value = 1
    } else if (command.type == 'delete') {
      deleteRole(command.id)
    }
  }

  const closeAdd = (val) => {
    addType.value = ''
    editor.value = null
    dialogInfoTradingAdd.value = val
  }

  const addRole = () => {
    addType.value = 'user_Role'
    dialogInfoTradingAdd.value = true
    editor.value = null
  }

  const confirmToReload = () => {
    addType.value = ''
    dialogInfoTradingAdd.value = false
    searchFunc()
  }

  const deleteRole = async (id) => {
    try {
      await ElMessageBox.confirm(t('Msg.Delete'), t('Msg.SystemPrompt'), {
        confirmButtonText: t('Btn.Confirm'),
        cancelButtonText: t('Btn.Cancel'),
        type: 'warning',
      })

      const res = await Service.roleListDelete({ id })
      if (res.code == Code.StatusOK) {
        pigeon.success(t('Msg.DeleteSuccess'))
        searchFunc()
      } else {
        pigeon.error(res.msg)
      }
    } catch (error) {
      // 用户取消删除
      console.log('删除操作取消')
    }
  }

  const searchFunc = async () => {
    pictLoading.value = true

    if (!display.value['R-Role-Search']?.show) {
      pigeon.warning(t('Msg.NotDisplay'))
      pictLoading.value = false
      return
    }
    console.log(search.date)
    // 处理日期
    if (search.date == null || search.date.length == 0) {
      search.startDate = ''
      search.endDate = ''
    } else {
      search.startDate = search.date[0]
      search.endDate = search.date[1]
    }

    try {
      const res = await Service.roleList({
        ...search,
        page: {
          current: pagerInfo.current,
          row: pagerInfo.row,
        },
      })

      if (res.code == Code.StatusOK) {
        mock_tableData.value = res.data
        if (res.page != null) {
          pagerInfo.rowTotal = res.page.rowTotal
          pagerInfo.pageTotal = res.page.pageTotal
        } else {
          pagerInfo.rowTotal = 0
        }
        pigeon.success(t('Msg.SearchSuccess'))
      } else {
        pigeon.error(res.msg)
      }
    } catch (error) {
      pigeon.error(t('Msg.SearchFail'))
    } finally {
      pictLoading.value = false
    }
  }
  const dateChange = (value) => {
    console.log(value)
  }

  const toSearch = () => {
    pagerInfo.current = 1
    searchFunc()
  }

  const handleSizeChange = (val) => {
    pagerInfo.row = val
    searchFunc()
  }

  const handleCurrentChange = (val) => {
    pagerInfo.current = val
    searchFunc()
  }

  // 挂载生命周期
  onMounted(() => {
    searchFunc()
  })
</script>

<style scoped lang="scss">
  #user_Role {
    .crm_search {
      .search_action_btn {
        .delete {
          background-color: #a1a1a1;
        }
        .delete.active {
          background-color: #368fec;
        }
      }
      .chooseLang {
        margin-top: 2px;
        margin-right: 10px;
        > span {
          border: 1px solid #dcdfe6;
          padding: 0 8px;
          min-width: 100px;
          display: inline-block;
          height: 32px;
          line-height: 32px;
          box-sizing: border-box;
          text-align: center;
        }
        span.active {
          background-color: #368fec;
          border-color: #368fec;
          color: #ffffff;
        }
      }
    }
    .el-table .state {
      display: inline-block;
      min-width: 80px;
      max-width: 150px;
      box-sizing: border-box;
      line-height: 1.5;
      border-radius: 2px;
      padding: 2px 10px;
      color: #ffffff;
    }
    .crm_verified_info_mask_trading {
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(43, 48, 67, 0.65);
      z-index: 88;
    }
  }
</style>
<style lang="scss">
  #user_Role {
    .dialog_header_w {
      .crm_search_down {
        width: 400px;
      }
    }
  }
</style>
