<template>
  <div>
    <el-dialog title="产品上线流程附件管理" v-model="isShow" width="50%">
      <crud-template
        ref="crudRef"
        class="as-weight"
        :home-data="field"
        :table-data="tableData"
        @btnSearch="btnSearch"
        @add="add"
        @handleEdit="handleEdit"
        @cancel="cancel"
        @submit="submit"
        @refreshLeft="refreshLeft"
        @CurrentChange="handleCurrentChange"
        @handleDelete="handleDelete"
        @pageSizeChange="
          (val) => {
            field.paging.currentPage = 1
            field.paging.pageSize = val
            // getList()
          }
        "
      >
        <template #operation="{ scope }">
          <el-button
            type="primary"
            size="small"
            @click.stop="handleDownload(scope.row)"
          >
            下载
          </el-button>
        </template>
        <template #status="item">
          <el-switch
            :model-value="item.scope.row.status"
            active-value="ENABLE"
            inactive-value="DISABLE"
            active-color="#ff4949"
            inactive-color="#13ce66"
            @click="handleBeforeChange(item.scope.row)"
          ></el-switch>
        </template>
      </crud-template>
    </el-dialog>
  </div>
</template>

<!-- 协议管理 -->
<script lang="ts" setup>
// @ts-ignore crudFrom模板
import CrudTemplate from '@/crud/index.vue'
import { ref, onMounted, computed, reactive, toRaw, watch } from 'vue'
import { ElMessage } from 'element-plus'
import BaseService from '@/utils/baseService'
import moment from 'moment'
import $storeinitData from '@/store/initData' //引入tab vuex
import { exportFn, importFn } from '@/views/settlement/exportFn'
import { IsPermission } from '@/router/routerUtil'
import { useRoute } from 'vue-router'
import { msgConfirm, typeTy } from '@/utils/msg'
import { Console } from 'console'
const route = useRoute()

const emit = defineEmits(['update:modelValue', 'handleExamine'])
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
    default: {}
  },
  IS_ENABLE: {
    type: Array,
    default: () => [],
  },
})

const isShow = computed({
  get: function () {
    if (props.modelValue) {
      getList()
    }
    return props.modelValue
  },
  set: function (newValue) {
    emit('update:modelValue', newValue)
  },
})
const productRowData = ref(props.rowData)
watch(
  () => props.rowData,
  (newData) => {
    productRowData.value = newData
  },
  {
    deep: true,
  }
)
// 协议管理******************************
const crudRef = ref()
const searchForm = ref({
  groupName: '',
})
const value1 = ref() // 筛选时间
const tableData = ref([])

//表单数据配置
const formLabelWidth = '180px'
const field = ref({
  tabSize: 'small', //Table 的尺寸 large / default /small (默认default)
  searchShow: false, //是否显示搜索模块(默认false)
  border: true, //是否添加边框(默认false)
  dialogCustom: false, //自定义Dialog (默认false)
  dialogFooter: false, //隐藏弹窗页脚显示 (默认false)
  dialogWidth: '40%', //dialog宽度 (默认40%)
  crudShow: true, //是否显示CURD操作栏 (默认true)
  crudChildShow: true, //是否显示CURD子操作栏 (默认true)
  paginStart: true, //是否显示分页查询 (默认false)
  isPageSizes: true,//是否修改分页pageSize
  pageLayout: 'total, sizes, prev, pager, next',
  titleDialog: '', //table 标题
  paging: {
    pageSize: 10,
    currentPage: 1,
    total: 0,
  },
  crud: {
    add: true,
  },
  searchOperation: {
    isDownload: false, // 导出
    isToLead: false, // 导入
    isAdd: false,
    isTransferMachine: false,
  },
  tableSize: -1,
  operateShow: true, //是否为表格添加操作栏(默认true)
  operateTitle: '操作', //操作栏标题(默认为"")
  operateFixed: false, //操作栏是否固定(默认false)
  operateWidth: '200', //操作栏宽度
  operate: {
    info: false, //详情
    edit: true, //是否编辑(默认true)
    delete: true, //是否删除(默认true)
    remark: false, // 查看
  },
  extend: [
    {
      type: 'index',
      label: '序号',
    },
  ],
  field: [
    {
      label: '附件名称',
      prop: 'fileName',
      form: {
        formLabelWidth: formLabelWidth,
        width: '90%',
        type: 'input',
        required: true,
      },
    },
    // {
    //   label: '附件上传',
    //   prop: 'fileUrl',
    //   hide: true,
    //   form: {
    //     width: '90%',
    //     formLabelWidth: formLabelWidth,
    //     type: 'upload',
    //     placeholder: '请上传附件',
    //     required: true,
    //   },
    // },
    {
      prop: 'status',
      label: '启用状态',
      slotSet: true,
      slotSetName: 'status',
      listData: props.IS_ENABLE,
    },
    {
      label: '补充文件类型',
      prop: 'typeName',
      form: {
        formLabelWidth: formLabelWidth,
        width: '90%',
        type: 'input',
        required: true,
      },
    },
    {
      label: '版本号',
      prop: 'version',
      form: {
        formLabelWidth: formLabelWidth,
        width: '90%',
        type: 'input',
        required: true,
      },
    },
  ],
})
const typeOption = ref('')
const consultativeRowData = ref()
// 编辑按钮
function handleEdit(idx: any, row: any) {
  typeOption.value = 'edit'
  consultativeRowData.value = row
}
// 新增按钮
function add() {
  typeOption.value = 'add'
}
// 提交
function submit(data: any) {
  let api = ''
  let datas = JSON.parse(JSON.stringify(toRaw(data)))
  if (typeOption.value === 'edit') {
    // 编辑
    api = '/managew/api/product/Attachment/update'
    datas.id = consultativeRowData.value.id
  } else {
    // 新增
    api = '/managew/api/product/Attachment/add'
  }
  datas.releaseId = productRowData.value.releaseId
  console.log(datas, 'datasdatas')
  BaseService.postN(api, datas).then((res: any) => {
    if (res && res.code === 0) {
      ElMessage.success('操作成功')
      console.log("提交调用")
      getList()
      cancel()
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 删除按钮
function handleDelete(idx: any, row: any) {
  const data = {
    id: row.id,
  }
  BaseService.postN('/managew/api/product/relaseAttachFiles/delete', {
    id: data.id,
  }).then((res: any) => {
    if (res && res.statusCode === 0) {
      ElMessage.success('操作成功')
      console.log("删除调用")
      getList()
      cancel()
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 取消
function cancel() {
  crudRef.value.reset()
  crudRef.value.dialogFormVisible = false
}
// 搜索按钮
function btnSearch() {
  field.value.paging.currentPage = 1
  console.log("搜索调用")
  getList()
}
// 搜索重置
function refreshLeft() {
  field.value.paging.currentPage = 1
  searchForm.value = {
    groupName: '',
  }
  value1.value = null
  tableData.value = []
  console.log("重置调用")
  getList()
}
// 获取列表
function getList(refresh?) {
  if (crudRef.value) crudRef.value.tableLoding = true
  // 参数
  let params: any = {
    releaseId: productRowData.value.releaseId,
    pageNo: field.value.paging.currentPage,
    pageSize: field.value.paging.pageSize,
  }
  // const searchFormList = { ...searchForm.value }
  // for (const key in searchFormList) {
  //   if (searchFormList[key]) {
  //     params[key] = searchFormList[key]
  //   }
  // }
  BaseService.postN(
    '/managew/api/product/Attachment/page',
    params
  ).then((res: any) => {
    if (res && res.code === 0) {
      tableData.value = res.data.result || []
      //分页总数
      field.value.paging.total = res.data.totalCount
      crudRef.value.tableLoding = false
    } else {
      crudRef.value.tableLoding = false
      ElMessage.error(res.message)
    }
  })
}
function handleCurrentChange(val: number) {
  field.value.paging.currentPage = val
  console.log("换页调用")
  getList()
}

//切换按钮 1 启用 0 停用
function handleBeforeChange(row) {
  let text = row.status == 'ENABLE' ? '停用' : '启用'
  msgConfirm(`请确认是否 ${text} ${row.fileName}`, typeTy.warning).then(() => {
    // do something
    const params = {
      id: row.id,
      status: row.status == 'ENABLE' ? 'DISABLE' : 'ENABLE',
    }
    console.log(params, 'paramsparams')
    BaseService.postN(
      '/managew/api/product/Attachment/status',
      params
    ).then((res: any) => {
      if (res && res.code === 0) {
        ElMessage.success(`${text}成功`)
        getList(true)
      } else {
        ElMessage.error(res.message)
      }
    })
  })
}
const handleDownload = (data) => {
  BaseService.getDownload(
    import.meta.env.VITE_APP_UPLOAD_URL + data.fileUrl,
    data.fileName,
    true
  )
}
</script>
