<script setup lang="ts">
import { ref, computed, unref, reactive, shallowRef } from "vue";
import { httpRoleQuery } from "/@/api/system/accountRole";
import { createReports, companies } from "./config"
import { useAsync } from "/@/hooks/core/useAsync";
import { ElForm, ElMessage } from "element-plus";
import { ModalTypes } from "./../types";

import { httpUpdate } from "/@/api/system/wechatManager";

const emit = defineEmits(["refresh"]);

const visible = ref(false);
const modalType = ref<ModalTypes>(ModalTypes.create);
const formRef = ref<InstanceType<typeof ElForm> | null>(null);

const reports = ref(createReports());

const defaultData = {
  mobile: "",
  nickname: "",
  is_show: []
};

const formData = ref<Record<string, any>>({ ...defaultData });

const { run, loading } = useAsync({
  success: () => { 
    emit("refresh");
    visible.value = false;
  },
  responseCode: 0
});

// 上线商品查询

const title = computed(() => {
  const baseName = "微信账号权限";
  switch (ModalTypes.value) {
    case ModalTypes.create:
      return "创建" + baseName;
    case ModalTypes.preview:
      return "查看" + baseName;
    default:
      return "修改" + baseName;
  }
});

const rules = reactive({
  nickname: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }]
});

function handleSave() {
  formRef.value.validate(isValid => {
    if (!isValid) return;
    let is_show = reports.value.filter(item => item.isOpen).map(({ permission_id }) => permission_id).join(",")

    const field_permission = reports.value.filter(item => item.needFieldPermission).map(({ fieldPermission }) => fieldPermission.join(",")).join(',')
    if (field_permission) {  is_show += `,${field_permission}` }

    const companyArr = companies.map(item => ({
      companyNo: item.value,
      companyName:item.label,
      info: reports.value.reduce((prev, current) =>  current.companyPermission.includes(item.value) ? [...prev, current.permission_id] : prev, [])
    }))

    const { id, nickname, mobile } = formData.value;
    const params = { id, mobile, is_show, nickname, companyArr }
    run(httpUpdate(params));
  });
}

defineExpose({
  onDisplay: (_data?: any, type?: ModalTypes) => {
    formData.value = { ...defaultData };
    modalType.value = type;
    visible.value = true;


    const _reports = createReports();
    const { mobile, nickname,id } = _data;
    let isShowArr = _data.is_show.split(',');

    _reports.forEach(item => { 
      if (isShowArr.includes('cost_field')) {
        isShowArr = isShowArr.filter((item) => item !== 'cost_field');
        const index = _reports.findIndex(({ permission_id }) => permission_id === 6);
        if (index !== -1) { _reports[index].fieldPermission = ['cost_field'];}
      }

      item.isOpen = isShowArr.includes(String(item.permission_id));
      if (item.needCompanyPermission) { 
        for (const key in _data.companyArr) {
          const company = _data.companyArr[key];

          if (!company.info) continue;
          
          if (company.info && company.info.includes(String(item.permission_id)) || company.info.includes(Number(item.permission_id))) { 
             item.companyPermission.push(company.companyNo);
          }
         }
      }
    })

    reports.value = _reports;
    formData.value = { id,mobile, nickname, is_show: _data.is_show.split(',') };
  }
});
</script>

<template>
  <ElDialog center v-model="visible" :title="title" :close-on-click-modal="false" width="1024px">
    <ElForm ref="formRef" labelWidth="100px" label-position="left" :model="formData" :rules="rules"
      :disabled="modalType === ModalTypes.preview" v-loading="loading">
      <ElFormItem label="真实姓名" prop="nickname">
        <ElInput placeholder="请输入真实姓名" v-model="formData.nickname" disabled />
      </ElFormItem>

      <ElFormItem label="手机号" prop="mobile" style="margin-bottom:10px">
        <ElInput placeholder="请输入手机号" v-model="formData.mobile" disabled />
      </ElFormItem>


      <ElFormItem label="可查看报表" required style="margin-bottom:0px;font-weight:700;" />

      <el-scrollbar height="350px">
        <div class="report">
        <div class="report__wrapper" v-for="(report,index) in reports" :key="reports[index].permission_id">
          <div class="left">
            <p>{{report.title}}</p>
            <el-switch v-model="reports[index].isOpen" />
          </div>
          
          <div class="right">
            <div class="company" v-if="reports[index].needCompanyPermission">
              <div class="title">业务公司</div>
              <el-checkbox-group v-model="reports[index].companyPermission" :disabled="!reports[index].isOpen">
                <el-checkbox 
                  v-for="company in companies" 
                  :key="company.value"
                  :label="company.value"
                >{{company.label}}</el-checkbox>
              </el-checkbox-group>
            </div>

            <div class="company"  v-if="reports[index].needFieldPermission">
              <div class="title">字段权限</div>
              <el-checkbox-group v-model="reports[index].fieldPermission" :disabled="!reports[index].isOpen">
                <el-checkbox label="cost_field">成本</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
      </el-scrollbar>


      <ElFormItem>
        <div class="flex w-full justify-end">
          <ElButton type="取消" @click="() => (visible = false)">取消</ElButton>
          <ElButton type="primary" @click="() => handleSave()">保存</ElButton>
        </div>
      </ElFormItem>
    </ElForm>
  </ElDialog>
</template>


<style lang="scss" scoped>
.report {
  margin-bottom:10px;
  &__wrapper{
    display:flex;
    border-bottom:1px solid #dfe6ec;
    border-right:1px solid #dfe6ec;

    &:first-child {
      border-top:1px solid #dfe6ec;
    }

    .left {
      min-width:100px;
      border:1px;
      border-right:1px solid #dfe6ec;
      border-left:1px solid #dfe6ec;
      display:flex;
      align-items:center;
      justify-content:center;
      flex-direction:column;
    }

    .right {
      flex:1;
      .company {
        display:flex;
        flex-direction: column;
        padding:0px 10px;
        width:100%;

        .title {
          border-bottom:1px dashed #dfe6ec;
          line-height:35px;
          color:#97a8be;
          font-size:16px;
        }
      }
    }
  }
}
</style>
