<script setup lang="ts">
import { ref, getCurrentInstance, reactive } from "vue";
import { useRouter } from "vue-router";
import request, { download } from '~/utils/request';
import { pick } from 'lodash-es';
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { AxiosRequestConfig } from 'axios'

// #region (constant)
const TABLE_KEY = 'id'
const URL_CUT = '/xdjy/wljy_kc_kkjl'
const URL_CUT_REF = ref(URL_CUT)
const URL_SUBMIT_KEY = URL_CUT.split('/').join('_').slice(1)
const instance = getCurrentInstance()
const router = useRouter()
// #endregion

// #region (variable)
const loading_table = ref(true)
let whichDialogSubmit: 'add' | 'edit'
// #endregion

// #region (type)
type TYPE_TABLE_FIELD = {
  [TABLE_KEY]: string;
  'name': string; // 开课名称
  'time': string; // 开课时间
  'experts_json': string; // 参与专家状态
  'teaching': string; // 教案
  'files': string; // 上传文件
  'xwk_id': string; // 所属课程编号
  'files_improve': string; // 改进后教案
  'expert_opinions': string; // 专家意见整理
}
// #endregion

// #region (props)
const props = defineProps<{
  aid: string,
  // 课程属性
  info: {
    'xwk_id': string;
    'xwk_kcmc': string; // 课程名称
    'xwk_kclx': string; // 课程类型
    'xwk_kt': string; // 课题
    'xwk_fqr': string; // 发起人
    'xwk_zt': string; // 状态
    'grade_id': string; // 年级编号
    'grade_name': string; // 年级名称
    'subject_id': string; // 学科编号
    'subject_name': string; // 学科名称
    'xwk_td': string; // 团队
    'xwk_sctp': string; // 上传图片
    'xwk_qtfj': string; // 其他附件
    'xwk_content': string; // 内容
  },
}>()
// #endregion

// #region (query row)
const queryForm_Data = ref<Partial<TYPE_TABLE_FIELD> & { keyword?: string }>({})

const handleQueryFormBtn_search = () => {
  queryApi()
}
const handleQueryFormBtn_clear = () => {
  queryForm_Data.value = {}
}
// #endregion

// #region (table selection)
const multipleSelection = ref<TYPE_TABLE_FIELD[]>([])
const handleSelectionChange = (val: TYPE_TABLE_FIELD[]) => {
  multipleSelection.value = val
}
// #endregion

// #region (table row)
const handleTableRowBtn_import = async ({ file }: { file: File }) => {
  const res = await API_MAP['import']({ file })
  if (res.code === '1') {
    queryApi()
    ElMessage.success(res.msg)
  }
}
const handleTableRowBtn_export = () => {
  if(multipleSelection.value.length===0) return ElMessage.info('请先勾选导出文件');exportApi({[TABLE_KEY]:multipleSelection.value.map((item: TYPE_TABLE_FIELD)=>item[TABLE_KEY])?.join()})
}
const handleTableRowBtn_add = () => {
  whichDialogSubmit = 'add'
  dialogForm_Data.value = { xwk_id: props.aid }
  dialogVisible_addOrEdit.value = true
}
const handleTableRowBtn_delete = async () => {
  if(multipleSelection.value.length===0) return ElMessage.info('请先勾选文件');const resp = await deleteApi(multipleSelection.value.map((item: TYPE_TABLE_FIELD) => item[TABLE_KEY]));if(resp.code!=='1')return;ElMessage.success('删除成功');
  queryApi()
}

const handleTableColBtn_improve = async (row: TYPE_TABLE_FIELD) => {
  whichDialogSubmit = 'edit'
  dialogForm_Data.value = pick(row, [`${TABLE_KEY}`, ...Object.keys(dialogForm_Rules_improve)])
  dialogVisible_improve.value = true
}
// #endregion

// #region (table body)
const tableData = ref<TYPE_TABLE_FIELD[]>([])

const handleTableColBtn_edit = async (scope: { row: TYPE_TABLE_FIELD }) => {
  whichDialogSubmit = 'edit'
  const res = await detailApi(scope.row[TABLE_KEY])
  dialogForm_Data.value = pick(res.data.one_info, [`${TABLE_KEY}`, ...Object.keys(dialogForm_Rules_addOrEdit)])
  dialogVisible_addOrEdit.value = true
}

const handleTableColBtn_delete = async (scope: { row: TYPE_TABLE_FIELD }) => {
  const resp = await deleteApi(scope.row[TABLE_KEY]);if(resp.code!=='1')return;ElMessage.success('删除成功');
  queryApi()
}
// #endregion

// #region (pagination)
const total = ref(0)
const limit = ref(10)

const currentPage = ref(1)
function handleCurrentChange() {
  queryApi()
}
// #endregion

// #region (dialog base)
const dialogForm_Data = ref<Partial<TYPE_TABLE_FIELD> & { keyword?: string }>({})

const handleDialogFormBtn_submit = async (formRefKey: string, extendData?: Partial<TYPE_TABLE_FIELD>) => {
  const isValid = await (instance?.refs[formRefKey] as FormInstance).validate((valid: boolean) => valid)
  if (isValid) {
    const resp = await API_MAP[whichDialogSubmit](<TYPE_TABLE_FIELD>({ ...dialogForm_Data.value, ...extendData }))
    if(resp.code!=='1')return;ElMessage.success('操作成功');handleDialogFormBtn_cancel()
    queryApi()
  }
}
const handleDialogFormBtn_cancel = (formRefKey?: string) => {
  dialogVisible_addOrEdit.value = false
  dialogVisible_improve.value = false
}
// #endregion

// #region (dialog add/edit)
const dialogVisible_addOrEdit = ref<boolean>(false)

const dialogForm_Ref_addOrEdit = ref<FormInstance>()
const dialogForm_Rules_addOrEdit = reactive({
  'name': { required: true, message: '开课名称不能为空', trigger: 'submit' },
  'time': { required: true, message: '开课时间不能为空', trigger: 'submit' },
  'experts_json': { required: true, message: '参与专家状态不能为空', trigger: 'submit' },
  // 'teaching': { required: true, message: '教案不能为空', trigger: 'submit' },
  // 'files': { required: true, message: '上传文件不能为空', trigger: 'submit' },
  'files': { required: true, message: '教案不能为空', trigger: 'submit' },
  // 'xwk_id': { required: true, message: '所属课程编号不能为空', trigger: 'submit' },
  // 'files_improve': { required: true, message: '改进后教案不能为空', trigger: 'submit' },
  // 'expert_opinions': { required: true, message: '专家意见整理不能为空', trigger: 'submit' },
})
// #endregion

// #region (dialog improve)
const dialogVisible_improve = ref<boolean>(false)

const dialogForm_Ref_improve = ref<FormInstance>()
const dialogForm_Rules_improve = reactive({
  // 'name': { required: true, message: '开课名称不能为空', trigger: 'submit' },
  // 'time': { required: true, message: '开课时间不能为空', trigger: 'submit' },
  // 'experts_json': { required: true, message: '参与专家状态不能为空', trigger: 'submit' },
  // 'teaching': { required: true, message: '教案不能为空', trigger: 'submit' },
  // 'files': { required: true, message: '上传文件不能为空', trigger: 'submit' },
  // 'files': { required: true, message: '教案不能为空', trigger: 'submit' },
  // 'xwk_id': { required: true, message: '所属课程编号不能为空', trigger: 'submit' },
  'files_improve': { required: true, message: '改进后教案不能为空', trigger: 'submit' },
  'expert_opinions': { required: true, message: '专家意见整理不能为空', trigger: 'submit' },
})
// #endregion


// #region (request api):
function queryApi() {
  loading_table.value = true
  return request({
    url: URL_CUT + '/index',
    data: {
      ...queryForm_Data.value,
      limit: limit.value,
      page: currentPage.value,
      xwk_id: props.aid
    }
  }).then((response: { data: { total_rows: string, page_data: TYPE_TABLE_FIELD[] } }) => {
    const { data } = response
    total.value = parseInt(data.total_rows)
    tableData.value = data.page_data
    return response
  }).then(() => {
    loading_table.value = false
  })
}

function addApi(data: TYPE_TABLE_FIELD) {
  return request({
    url: URL_CUT + '/add',
    data: {
      [URL_SUBMIT_KEY]: data,
    }
  })
}

function editApi(data: Partial<TYPE_TABLE_FIELD>) {
  return request({
    url: URL_CUT + '/edit',
    data: {
      [TABLE_KEY]: data[TABLE_KEY],
      [URL_SUBMIT_KEY]: pick(data, ['name', 'time', 'experts_json', 'teaching', 'files', 'xwk_id', 'files_improve', 'expert_opinions',]),
    }
  })
}

function deleteApi(id: string | string[]) {
  return request({
    url: URL_CUT + '/delete',
    data: {
      [TABLE_KEY]: id,
    }
  })
}

function detailApi(id: string) {
  return request({
    url: URL_CUT + '/detail',
    data: {
      [TABLE_KEY]: id,
    }
  })
}

function importApi(data: { file: File }) {
  return request({
    $type: 'import',
    url: URL_CUT + '/import',
    data
  } as AxiosRequestConfig)
}

function exportApi(d) {
  return download(URL_CUT + '/index', {...queryForm_Data.value,...d})
}

const API_MAP = {
  query: queryApi,
  add: addApi,
  edit: editApi,
  delete: deleteApi,
  detail: detailApi,
  import: importApi,
  export: exportApi,
}
// #endregion

// #region (page init)
function init() {
  queryApi()
}
init()
// #endregion


const tabsValue = ref(0)

defineExpose({
  add: handleTableRowBtn_add
})

// #region (other dialog add/edit)
type TYPE_OTHER_TABLE_FIELD = {
  'xwj_kcmc': string; // 课程名称
  'xwj_kt': string; // 课题
  'xwj_scr': string; // 上传人
  'xwj_ja': string; // 教案
  'xwj_xa': string; // 学案
  'xwj_jpksp': string; // 精品课视频
  'grade_id': string; // 年级编号
  'xwj_jxcg': string; // 教学成果
  'grade_name': string; // 年级名称
  'xwj_jxfs': string; // 教学反思
  'subject_id': string; // 学科编号
  'subject_name': string; // 学科名称
  'xwk_id': string
}
const other_dialogForm_Data = ref<
  // 精品课属性
  Partial<TYPE_OTHER_TABLE_FIELD>
>({})

const other_dialogVisible_addOrEdit = ref<boolean>(false)

const other_dialogForm_Ref_addOrEdit = ref<FormInstance>()
const other_dialogForm_Rules_addOrEdit = reactive({
  'xwj_kcmc': { required: true, message: '课程名称不能为空', trigger: 'submit' },
  'xwj_kt': { required: true, message: '课题不能为空', trigger: 'submit' },
  'xwj_scr': { required: true, message: '上传人不能为空', trigger: 'submit' },
  'xwj_ja': { required: true, message: '教案不能为空', trigger: 'submit' },
  'xwj_xa': { required: true, message: '学案不能为空', trigger: 'submit' },
  'xwj_jpksp': { required: true, message: '精品课视频不能为空', trigger: 'submit' },
  'grade_id': { required: true, message: '年级编号不能为空', trigger: 'submit' },
  'xwj_jxcg': { required: true, message: '教学成果不能为空', trigger: 'submit' },
  'grade_name': { required: true, message: '年级名称不能为空', trigger: 'submit' },
  'xwj_jxfs': { required: true, message: '教学反思不能为空', trigger: 'submit' },
  'subject_id': { required: true, message: '学科编号不能为空', trigger: 'submit' },
  'subject_name': { required: true, message: '学科名称不能为空', trigger: 'submit' },
})



const handleTableColBtn_other = () => {
  other_dialogForm_Data.value = {
    grade_id: props.info.grade_id,
    grade_name: props.info.grade_name,
    subject_id: props.info.subject_id,
    subject_name: props.info.subject_name,
    xwj_scr: props.info.xwk_fqr,
    xwj_kt: props.info.xwk_kt,
    xwk_id: props.info.xwk_id
  }

  other_dialogVisible_addOrEdit.value = true
}



const handleOtherDialogFormBtn_submit = async (formRefKey: string, extendData?: Partial<TYPE_OTHER_TABLE_FIELD>) => {
  const isValid = await (instance?.refs[formRefKey] as FormInstance).validate((valid: boolean) => valid)
  if (isValid) {
    await request({
      url: '/xdjy/wljy_jpkc' + '/add',
      data: {
        xdjy_wljy_jpkc: other_dialogForm_Data.value,
      }
    })
    handleOtherDialogFormBtn_cancel()
  }
}
const handleOtherDialogFormBtn_cancel = (formRefKey?: string) => {
  other_dialogVisible_addOrEdit.value = false
}
// #endregion

const getJson = (str: string) => str.split(';').map((name: string) => ({ name, sfcj: '是' }))
</script>

<template>
  <template v-if="!loading_table">
    <el-empty v-if="tableData.length === 0" description="还未开课，请先开课" />
    <div v-else class="relative">
      <!-- <el-table :data="tableData" @selection-change="handleSelectionChange" v-loading="loading_table"
        element-loading-background="#ffffff70">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="name" label="开课名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="time" label="开课时间" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="experts_json" label="参与专家状态" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="teaching" label="教案" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="files" label="上传文件" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xwk_id" label="所属课程编号" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="files_improve" label="改进后教案" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="expert_opinions" label="专家意见整理" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_edit(scope)" type="primary">编辑
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_audit(scope)" type="primary">审核
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_detail(scope)" type="primary">详情
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_delete(scope)" type="primary">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table> -->
      <el-button class="absolute top-2px right-2px z-5" size="default" @click="handleTableColBtn_other" type="success">
        正式精品课展示
      </el-button>

      <el-tabs v-model="tabsValue">
        <el-tab-pane v-for="(item, idx) in tableData" :label="item.name" :name="idx" class="relative">
          <el-button class="absolute top-2px right-2px z-5" size="default" @click="handleTableColBtn_improve(item)"
            type="primary" v-if="!item.files_improve">意见整理
          </el-button>


          <div class="flex text-gray-500">
            <div>开课时间：</div>
            <div>{{ item.time }}</div>
          </div>
          <div class="flex text-gray-500">
            <div class="flex-none">参与专家状态：</div>
            <!-- <div>{{ item.experts_json }}</div> -->
            <div class="w-300px flex-none">
              <el-table :data="getJson(item.experts_json)">
                <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                <el-table-column prop="sfcj" label="是否参加" width="180"></el-table-column>
              </el-table>
            </div>

          </div>
          <div class="flex text-gray-500">
            <div class="flex-none">教案：</div>
            <!-- <div>{{ item.files }}</div> -->
            <file-link :file="item.files"></file-link>
          </div>

          <template v-if="!!item.files_improve">
            <div class="divider my-4"></div>
            <div class="relative">
              <el-button class="absolute top-2px right-2px z-5" size="default" @click="handleTableColBtn_improve(item)"
                type="primary">编辑
              </el-button>
              <div class="flex flex-col">
                <div class="pre">改进后教案：</div>
                <file-link :file="item.files_improve"></file-link>
              </div>
              <div class="flex flex-col mt-4">
                <div class="pre">专家意见整理</div>
                <div class="area h-160px">{{ item.expert_opinions }}</div>
              </div>
            </div>

          </template>

        </el-tab-pane>
      </el-tabs>
    </div>
  </template>


  <el-dialog v-model="dialogVisible_addOrEdit" append-to-body destroy-on-close>
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_addOrEdit" :rules="dialogForm_Rules_addOrEdit"
      label-width="120px">
      <el-form-item label="开课名称" prop="name">
        <el-select v-model="dialogForm_Data.name" clearable class="w-full">
          <el-option label="第一次开课" value="第一次开课"></el-option>
          <el-option label="第二次开课" value="第二次开课"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开课时间" prop="time">
        <!-- https://github.com/element-plus/element-plus/issues/8965 -->
        <str-to-arr v-model="dialogForm_Data.time" affix=" - ">
          <template #default="{ value, change }">
            <el-date-picker type="datetimerange" :model-value="value" value-format="YYYY-MM-DD HH:mm:ss" clearable
              @update:modelValue="(val: unknown) => change(val)"></el-date-picker>
          </template>
        </str-to-arr>
      </el-form-item>
      <el-form-item label="参与专家状态" prop="experts_json">
        <!-- <el-input v-model="dialogForm_Data.experts_json" type="textarea" /> -->
        <str-to-arr v-model="dialogForm_Data.experts_json">
          <template #default="{ value, change }">
            <el-select multiple filterable allow-create default-first-option :reserve-keyword="false"
              :model-value="value" @change="change" class="w-full" />
          </template>
        </str-to-arr>
      </el-form-item>
      <!-- <el-form-item label="教案" prop="teaching">
        <el-input v-model="dialogForm_Data.teaching" type="textarea" />
      </el-form-item>
      <el-form-item label="上传文件" prop="files">
        <el-input v-model="dialogForm_Data.files" clearable />
      </el-form-item> -->
      <el-form-item label="教案" prop="files">
        <file-upload v-model:full="dialogForm_Data.files" />
      </el-form-item>
      <!-- <el-form-item label="所属课程编号" prop="xwk_id">
        <el-input v-model="dialogForm_Data.xwk_id" clearable />
      </el-form-item> -->
      <!-- <el-form-item label="改进后教案" prop="files_improve">
        <file-upload v-model:full="dialogForm_Data.files_improve" />
      </el-form-item>
      <el-form-item label="专家意见整理" prop="expert_opinions">
        <el-input v-model="dialogForm_Data.expert_opinions" type="textarea" />
      </el-form-item> -->
      <div class="flex justify-center">
        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_addOrEdit')" type="primary">提交</el-button>
        <el-button @click="handleDialogFormBtn_cancel('dialogForm_Ref_addOrEdit')" type="default">取消</el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog v-model="dialogVisible_improve" append-to-body destroy-on-close>
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_improve" :rules="dialogForm_Rules_improve"
      label-width="120px">
      <el-form-item label="改进后教案" prop="files_improve">
        <file-upload v-model:full="dialogForm_Data.files_improve" />
      </el-form-item>
      <el-form-item label="专家意见整理" prop="expert_opinions">
        <el-input v-model="dialogForm_Data.expert_opinions" type="textarea" />
      </el-form-item>
      <div class="flex justify-center">
        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_improve')" type="primary">提交</el-button>
        <el-button @click="handleDialogFormBtn_cancel('dialogForm_Ref_improve')" type="default">取消</el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog v-model="other_dialogVisible_addOrEdit" append-to-body destroy-on-close>
    <el-form :model="other_dialogForm_Data" ref="other_dialogForm_Ref_addOrEdit"
      :rules="other_dialogForm_Rules_addOrEdit" label-width="120px">
      <el-form-item label="课程名称" prop="xwj_kcmc">
        <el-input v-model="other_dialogForm_Data.xwj_kcmc" clearable />
      </el-form-item>
      <!-- <el-form-item label="课题" prop="xwj_kt">
        <el-input v-model="other_dialogForm_Data.xwj_kt" clearable />
      </el-form-item> -->
      <!-- <el-form-item label="年级编号" prop="grade_id">
        <el-input v-model="other_dialogForm_Data.grade_id" clearable />
      </el-form-item> -->
      <!-- <el-form-item label="年级名称" prop="grade_name">
        <remote-select to="grade" v-model="other_dialogForm_Data.grade_id"
          v-model:modelName="other_dialogForm_Data.grade_name">
        </remote-select>
      </el-form-item>
      <el-form-item label="学科名称" prop="subject_name">
        <remote-select to="subject" v-model="other_dialogForm_Data.subject_id"
          v-model:modelName="other_dialogForm_Data.subject_name">
        </remote-select>
      </el-form-item>
      <el-form-item label="上传人" prop="xwj_scr">
        <el-input v-model="other_dialogForm_Data.xwj_scr" clearable />
      </el-form-item> -->
      <el-form-item label="教案" prop="xwj_ja">
        <file-upload v-model:full="other_dialogForm_Data.xwj_ja" />
      </el-form-item>
      <el-form-item label="学案" prop="xwj_xa">
        <file-upload v-model:full="other_dialogForm_Data.xwj_xa" />
      </el-form-item>
      <el-form-item label="精品课视频" prop="xwj_jpksp">
        <!-- <el-input v-model="other_dialogForm_Data.xwj_jpksp" type="textarea" /> -->
        <file-upload v-model:full="other_dialogForm_Data.xwj_jpksp" />
      </el-form-item>

      <el-form-item label="教学成果" prop="xwj_jxcg">
        <el-input v-model="other_dialogForm_Data.xwj_jxcg" type="textarea" />
      </el-form-item>

      <el-form-item label="教学反思" prop="xwj_jxfs">
        <el-input v-model="other_dialogForm_Data.xwj_jxfs" type="textarea" />
      </el-form-item>
      <!-- <el-form-item label="学科编号" prop="subject_id">
        <el-input v-model="other_dialogForm_Data.subject_id" clearable />
      </el-form-item> -->

      <div class="flex justify-center">
        <el-button @click="handleOtherDialogFormBtn_submit('other_dialogForm_Ref_addOrEdit')" type="primary">提交
        </el-button>
        <el-button @click="handleOtherDialogFormBtn_cancel('other_dialogForm_Ref_addOrEdit')" type="default">取消
        </el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
