<template>
  <div class="admin-pcba-editInfo">
    <el-dialog :title="formData.titleText" v-model="formData.isShowDialog" draggable width="769px">
      <el-form :model="formData.editData"
               :rules="rules"
               ref="formRef"
               v-loading="formData.loading"
               size="default"
               label-width="80px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="主板类型" prop="boardtype">
              <el-input v-model="formData.editData.boardType" placeholder="请输入主板类型" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>




<table id="myTable">
    <tr>
      <th>选择</th>
      <th>功能码</th>
      <th>功能名称</th>
    </tr>
  </table>



      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" icon="ele-CircleClose" size="default">取 消</el-button>
          <el-button type="primary" :icon="formData.editIcon" @click="onSubmit" size="default">{{formData.buttonText}}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>



</template>





<script setup lang="ts">
import {FormRules} from "element-plus";
import { reactive,onMounted,ref, watch} from "vue";
import { BoardAllFunctionAPI } from '/@/api/admin/PCBA/boardAllFunctionApi'
import { BoardAllFunctionDto } from '/@/api/admin/PCBA/boardAllFunctionDto'
import { BoardFunctionListApi } from '/@/api/admin/PCBA/boardFunctionListApi'
import { BoardFunctionListDto } from '/@/api/admin/PCBA/boardFunctionListDto'
import eventBus from "/@/utils/mitt";


var addlist = [];

const getSelectedValues =  () => {
var checkboxes = document.querySelectorAll('input[name="options"]:checked');
var selectedValues = [];
checkboxes.forEach(function(checkbox) {
    selectedValues.push(checkbox.value);
});
//alert("选中的值: " + selectedValues.join(", "));
addlist = selectedValues;
}




const addCheckbox =  () => {

var checkboxes = document.querySelectorAll('input[name="options"]');
console.log(checkboxes.length)
if(checkboxes.length!=0)
{
  return;
}

let list = formData.all_list;
console.log(list)

for(let i = 0;i<list.length;i++)
{
    
let data = list[i];


      var table = document.getElementById("myTable");
      var row = table.insertRow();

      var cell1 = row.insertCell();
      var cell2 = row.insertCell();
      var cell3 = row.insertCell();





      cell1.innerHTML = '<input type="checkbox" name="options" value="'+data.code + '">';
      cell2.innerHTML = data.code;
      cell3.innerHTML = data.name;
    }
}





enum Form {
  ADD,
  UPDATE
}

/**数据对象 */
const formData = reactive({
  loading: false,
  formType: Form.ADD,
  titleText:'',
  editIcon:'',
  buttonText:'',
  isShowDialog: false,
  //表单数据对象
  editData:{} as BoardFunctionListDto,
  all_list:[]
})

// /**有效时间选择校验*/
// const validateDate = (rule: any, value: any, callback: any) => {
//   if(new Date(value).getTime() > Date.now()){
//     callback()
//   }else{
//     callback(new Error('选择的时间已失效'))
//   }
// }

/**表单校验*/
const rules = reactive<FormRules>({
  code: [
    { required: true, message: '请输入功能码', trigger: 'blur' },
  ],

})



onMounted(() => {
    init()
    eventBus.off('refreshView')
    eventBus.on('refreshView', async () => {
      await init()
    })

  })

        /**初始化 */
        const init = async () => {
          addCheckbox()
        }



/**
 * 表单对象
 */
const formRef = ref()


/**
 * 根据参数 打开表单
 * @param val
 */
const openDialog = (type,val) => {


console.log(val)
  formData.all_list = val;
  
  
  var table = document.getElementById("myTable");
  if(table != null)
  {
    init();
  }
  
  if(type==1){


   // formData.editData = JSON.parse(JSON.stringify(({...val})))
    formData.titleText = '更新'
    formData.buttonText = '更新'
    //更新操作
    formData.formType = Form.UPDATE
    formData.editIcon = 'ele-Refresh'
  }else {


    //formData.editData = {} as BoardAllFunctionDto
    formData.titleText = '添加'
    formData.buttonText = '添加'
    //添加操作
    formData.formType = Form.ADD
    formData.editIcon = 'ele-CirclePlus'
  }
  formData.isShowDialog = true


}

/**
 * 取消
 */
const onCancel = () => {
  formData.editData = {} as BoardAllFunctionDto
  formData.isShowDialog = false
}

/***监听弹窗关闭表单验证*/
watch(() => formData.isShowDialog,(newVal) => {
  if(newVal) formRef.value?.resetFields()
})

/**
 * 提交前表单验证
 */
const onSubmit =  () => {
  formRef.value.validate(async (valid: boolean) =>{
    if(!valid) return

    formData.loading = true
    let res = {} as any
    if(formData.formType == Form.UPDATE){

     // res = await new BoardAllFunctionAPI().Update(formData.editData as BoardAllFunctionDto).catch(() => {
    //    formData.loading = false
    //  })
      
    }else if(formData.formType == Form.ADD){
     
      getSelectedValues();

    for(var i = 0;i< addlist.length;i++)
    {
        var data ={} as BoardFunctionListDto;
        data.boardType = formData.editData.boardType;
        data.code = addlist[i];
        console.log(data)
        res = await new BoardFunctionListApi().insert(data).catch(() => {
          formData.loading = false
        })
        console.log(res)

    }


     // res = await new BoardAllFunctionAPI().Insert(formData.editData as BoardAllFunctionDto).catch(() => {
     //   formData.loading = false
    //  })
    }else {
      formData.loading = false
      return
    }

    if(res?.data){
      eventBus.emit('refreshView')
      formData.isShowDialog = false
      formData.editData = {}
    }

    formData.loading = false
  })
}


defineExpose({
  openDialog,
})

</script>
<style scoped lang="scss">

</style>
