<template>
  <div class="layout-container">
    <!-- 菜单栏 -->
    <From :form-items="dynamicFormItems" @formSubmitted="handleFormSubmitted" @formReset="handleFormReset"
      :is_add_button="checkPermission('permission') ? '新增' : null" @addForm="edit" />

    <!-- 表格 -->
    <div class="layout-container">
      <Table @getTableData="changeTableData" v-model:page="page" ref="table" :data="tableData"
        @selection-change="handleSelectionChange">
        <el-table-column prop="appId" label="应用ID" />
        <el-table-column prop="appName" label="应用名称" width="150" />
        <el-table-column prop="superiorName" label="所属应用" width="120" />
        <el-table-column prop="ditchName" label="渠道名称" width="140">
          <template #default="scope">
            <el-tag type="success" effect="dark" v-if="scope.row.ditchName">
              {{ scope.row.ditchName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nickName" label="所属用户" width="140" />
        <el-table-column prop="appType" label="应用类型" width="90">
          <template #default="scope">
            {{ getDictionaryName("app_type", scope.row.appType) }}
          </template>
        </el-table-column>
        <el-table-column prop="apkUrl" label="下载链接" width="180">
          <template #default="scope">
            <a v-if="scope.row.apkUrl" :href="scope.row.apkUrl" target="_blank">{{ scope.row.appName }}.apk</a>
          </template>
        </el-table-column>
        <el-table-column prop="qrCode" width="130" label="二维码">
          <template #default="scope">
            <el-image v-if="scope.row.qrCode" style="width: 100px; height: 100px;" :z-index="99999"
              :src="scope.row.qrCode" fit="fill" :preview-src-list="[scope.row.qrCode]" preview-teleported="true" />
          </template>
        </el-table-column>
        <el-table-column prop="updateTips" label="更新提示" width="140" />
        <el-table-column prop="enabled" label="是否启用" width="90">
          <template #default="scope">
            {{ getDictionaryName("enabled", scope.row.enabled) }}
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="推广人" width="90">
          <template #default="scope">
            <div>
              <div>{{ scope.row.promoterUserLoginName }}</div>
              <div v-if="scope.row.promoterUserShareRate">{{ scope.row.promoterUserShareRate }}%</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130" v-permission="'permission'">
          <template #default="scope">
            <div class="button">
              <div>
                <el-link class="button-item" type="primary" style="margin-bottom: 5px" @click="edit(scope.row)">
                  编辑
                </el-link>
                <el-popconfirm placement="left" title="确认删除该数据?" @confirm="removeApp(scope.row)">
                  <template #reference>
                    <el-link class="button-item" style="margin-bottom: 5px" type="warning">删除</el-link>
                  </template>
                </el-popconfirm>
              </div>
              <!-- <div>
                <el-link class="button-item" type="primary" style="margin-bottom: 5px"
                  @click="assignPromoter(scope.row)">
                  分配
                </el-link>
                <el-popconfirm v-if="scope.row.promoterUserId" placement="left" title="确认取消该应用的分配?"
                  @confirm="closePromoter(scope.row)">
                  <template #reference>
                    <el-link class="button-item" style="margin-bottom: 5px" type="warning">取消分配</el-link>
                  </template>
                </el-popconfirm>
              </div> -->
            </div>
          </template>
        </el-table-column>
      </Table>
    </div>
    <!-- 操作弹窗 -->
    <Layer :layer="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
      <el-form :model="formEdit" :rules="rules" ref="ruleForm" label-width="130px" style="margin-right: 30px">
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="应用名称：" required prop="appName">
              <el-input v-model="formEdit.appName" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="应用类型：" prop="appType">
              <el-select v-model="formEdit.appType">
                <el-option v-for="item in getOptions('app_type')" :key="item.label" :value="item.value" :label="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="出包渠道：" required prop="ditchId">
              <el-select v-model="formEdit.ditchId">
                <el-option v-for="item in ditchListData" :key="item.ditchId" :value="item.ditchId"
                  :label="item.ditchName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="所属应用：" required prop="superiorId">
              <el-select v-model="formEdit.superiorId">
                <el-option v-for="item in issuedAppData" :key="item.appId" :value="item.appId" :label="item.appName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="版本号：" prop="versionCode">
              <el-input v-model="formEdit.versionCode" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="收益显示比率：" required prop="revenueDisplayRate">
              <el-input-number v-model="formEdit.revenueDisplayRate" :precision="2" :step="0.1" :min="0" :max="100" />
              <text style="margin-left: 5px;font-size: 18px;">%</text>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-form-item label="更新提示：" prop="updateTips">
          <el-input v-model="formEdit.updateTips" type="textarea" placeholder="请输入" clearable />
        </el-form-item>
      </el-form>
    </Layer>

    <!-- 分配推广人 -->
    <Layer :layer="layer1" @confirm="submit1(ruleForm1)" @close="layer1.show = false">
      <el-form :model="formEdit1" :rules="rules1" ref="ruleForm1" label-width="130px" style="margin-right: 30px">
        <el-form-item label="推广人：" required prop="userId">
          <el-select v-model="formEdit1.userId" style="width: 100%">
            <el-option v-for="item in promoterList" :key="item.userId" :value="item.userId" :label="item.nickName" />
          </el-select>
        </el-form-item>
        <el-form-item label="分成比率：" required prop="shareRate">
          <el-input-number v-model="formEdit1.shareRate" :precision="2" :step="0.1" :min="0" :max="100" />
          <text style="margin-left: 5px;font-size: 18px;">%</text>
        </el-form-item>
      </el-form>
    </Layer>
  </div>
</template>
<script setup>
import { onBeforeMount, ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { useGetDictList } from "@/hooks/useGetDictList.js";
import {
  appList,
  saveOrUpdate,
  delApp, issuedApps
} from "@/api/formworkErection.js";
import { ditchList } from '@/api/outBagModule.js'
import From from "@/components/from/index.vue";
import Table from "@/components/table/index.vue";
import Layer from "@/components/layer/index.vue";
import { usePermission } from '@/hooks/usePermission.js'
import { promoterUserAssignment, promoterUserAssignmentDelete, promoterUserQueryList } from "@/api/outBagModule.js";

const { checkPermission } = usePermission()
const { loadDictData, getDictionaryName, getOptions } = useGetDictList();
const tableData = ref([]);

// 分页参数, 供table使用
const page = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0,
});

const formSearch = ref({
  appName: null,
  channelName: null,
  appType: null,
  page: 1, // 当前页码
  limit: 20, // 当前页数量(查询量)
});

const dynamicFormItems = ref([]);

onBeforeMount(() => {
  settingData();
  getList();
  getDitchList();
  getIssuedAppList()
  // getPromoterList()
});



// 获取缓存数据设置筛选数据
const settingData = () => {
  loadDictData().then(() => {
    dynamicFormItems.value = [
      {
        label: "应用名称",
        prop: "appName",
        type: "input",
        needEnterEvent: true
      },
      {
        label: "应用类型",
        prop: "appType",
        type: "select",
        options: getOptions('app_type')
      },
    ];
  });
};
// 获取出包渠道
const ditchListData = ref([])
const getDitchList = async () => {
  let res = await ditchList({
    page: 1,
    limit: 999,
  })
  ditchListData.value = res.data
}
const issuedAppData = ref([])
const getIssuedAppList = async () => {
  let res = await issuedApps({})
  issuedAppData.value = res.data
}

function findByDitchName(ditchId) {
  return ditchListData.value.find(item => item.ditchId === ditchId)
}

// 分页数据
const getList = async () => {
  let res = await appList({ ...formSearch.value });
  tableData.value = res.data;
  page.total = res.pageMeta.total;
};

const changeTableData = (type) => {
  console.log('type :===>>', type);
  console.log(' page.pageNum:===>>', page.pageNum);
  formSearch.value.page = type ? 1 : page.pageNum;
  formSearch.value.limit = page.pageSize;
  // 分页切换
  getList();
};



// 搜索
const handleFormSubmitted = (formData) => {
  console.log("接收到子组件传递的数据", formData);
  formSearch.value.page = page.pageNum;
  formSearch.value.limit = page.pageSize;
  formSearch.value.channelName = formData?.channelName;
  formSearch.value.appName = formData?.appName;
  formSearch.value.appType = formData?.appType;

  getList();
};

// 表单重置
const handleFormReset = () => {
  formSearch.value = {
    appName: null,
    channelName: null,
    appType: null,
    page: 1, // 当前页码
    limit: 20, // 当前页数量(查询量)
  };
  page.pageNum = 1
  page.pageSize = 20
  page.total = 0
  getList();
};

// 选择监听器
const handleSelectionChange = (val) => {
  context.emit("selection-change", val);
};

// 弹窗
const layer = ref({
  show: false,
  title: "新增App",
  showButton: true,
  width: "60vw",
  edit: false,
});
const formEdit = ref({
  ditchId: null, //渠道ID
  ditchName: '',//渠道名称
  category: "",
  sub_category: "",
  versionCode: "",
  updateTips: "",
  appId: "",
  appName: "",
  qrCode: "",
  apkUrl: "",
  superiorId: '',
  revenueDisplayRate: '',//收益,显示比例
});

const edit = (row) => {
  ruleForm.value?.resetFields();
  if (row) {
    layer.value.title = "编辑APP";
    layer.value.edit = true;
    formEdit.value = row;
    formEdit.value.ditchId = Number(row.ditchId)
    formEdit.value.revenueDisplayRate = Number(row.revenueDisplayRate)

  } else {
    layer.value.title = "新增APP";
    layer.value.edit = false;
    formEdit.value = {};
  }
  layer.value.show = true;
};

const ruleForm = ref(null);

const rules = reactive({
  ditchId: [
    { required: true, message: "请选择出包渠道", trigger: "change" },
  ],
  superiorId: [
    { required: true, message: "请选择所属应用", trigger: "change" },
  ],
  appName: [
    { required: true, message: "请输入应用名称", trigger: "blur" },
  ],
  appType: [
    { required: true, message: "请输入应用类型", trigger: "blur" },
  ],
  versionCode: [
    { required: true, message: "请输入版本号", trigger: "blur" },
  ],
  revenueDisplayRate: [
    { required: true, message: "请输入收益显示比率", trigger: "blur" },
  ],
});

const submit = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (formEdit.value.store_on_sale === 2 && !formEdit.value.store_url && !formEdit.value.store_type) {
      ElMessage.error('上架商店或商店链接不能为空')
      return
    }

    if (valid) {
      let item = findByDitchName(formEdit.value.ditchId)
      formEdit.value.ditchName = item.ditchName
      formEdit.value.revenueDisplayRate = String(formEdit.value.revenueDisplayRate)
      // 提交内容
      if (layer.value.edit) {
        //api修改需要uuid
        formEdit.value.uuid = formEdit.value.appId;
      }
      const result = await saveOrUpdate({ ...formEdit.value });
      console.log(result)
      if (result.code === 200) {
        if (layer.value.edit) {
          ElMessage.success("修改成功");
          layer.value.show = false;
        } else {
          ElMessage.success("新增成功");
          layer.value.show = false;
        }
        getList();
      } else {
        ElMessage.error(result.msg);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// #region 分配推广人

// 获取推广人列表
const promoterList = ref([])
const getPromoterList = async () => {
  const res = await promoterUserQueryList({ page: 1, limit: 999 })
  promoterList.value = res.data
}

// 弹窗
const layer1 = ref({
  show: false,
  title: "分配推广人",
  showButton: true,
  width: "30vw",
  edit: false,
});
const formEdit1 = ref({
  appId: "",
  ditchId: 0,
  endTime: undefined,
  shareRate: "", //分成比率
  startTime: undefined,
  userId: "", //推广人
});

const assignPromoter = (row) => {
  ruleForm1.value?.resetFields();
  formEdit1.value = {}

  formEdit1.value.appId = row.appId
  formEdit1.value.ditchId = row.ditchId
  layer1.value.show = true;
};

const ruleForm1 = ref(null);

const rules1 = reactive({
  userId: [
    { required: true, message: "请选择推广人", trigger: "change" },
  ],
  shareRate: [
    { required: true, message: "请输入分成比率", trigger: "blur" },
  ],
});

const submit1 = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('数据 :===>>', formEdit1.value);
      formEdit1.value.shareRate = String(formEdit1.value.shareRate)
      await promoterUserAssignment({ ...formEdit1.value }).then(() => {
        ElMessage.success('分配成功')
        layer1.value.show = false
        getList();
      }).catch(() => {
        ElMessage.error('分配失败，请重试！')
      })
    } else {
      console.log("error submit!", fields);
    }
  });
};

//取消分配
const closePromoter = async (row) => {
  await promoterUserAssignmentDelete({
    appId: row.appId,
    userId: row.promoterUserId
  }).then(() => {
    ElMessage.success('取消分配成功')
    getList();
  }).catch(() => {
    ElMessage.error('取消分配失败，请重试！')
  })
}

// #endregion

// 删除
const removeApp = async (row) => {
  await delApp({ appId: row.appId }).then((res) => {
    ElMessage.success("删除成功");
    getList();
  });
};

</script>

<style scoped lang="scss">
.layout-container {
  .card {
    .title {
      margin-bottom: 10px;
      font-weight: 600;
    }

    display: flex;
    flex-direction: column;
    align-items: start;
    width: calc(100% - 60px);
    margin: 30px 30px 0;
  }

  .button {
    display: flex;
    flex-direction: column;

    .button-item {
      margin: 4px;
    }
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px solid #e4e7ed;
}

:deep(.el-image-viewer__wrapper) {
  z-index: 9999 !important;
}
</style>