import {
  addFormVariables, addFunction, addVariables
} from './script.js';

import {
  addCode
} from './template.js';
import { getInputCode } from './input.js';

const elementEnum = {
  'input': getInputCode
};
const getFormField = (tier, formData, elementData) => {
  let res = `pageForm`;
  if (tier && tier.length > 0) {
    tier.forEach((item, index) => {
      res += `['${item}']`;
    });
  }
  // if (formData !== '') {
  //   res += `['${formData}']`;
  // }
  if (elementData !== '') {
    res += `['${elementData}']`;
  }
  return res;
};

const getTableCode = (data) => {
  let isForm = data.isForm || false;
  let tier = data.tier || [];
  let tableData = data.elementData || {};
  let prefix = tableData.options.key || ('table_' + tableData.options.uuid);
  let formData = data.formData || {};
  if (isForm) {
    addCode(`<el-form-item label="${tableData.options.name || ''}" :required="${tableData.options.required}">`);
  } else {

  }
  if (tableData.options.isOperate) {
    addCode(`<div style="margin-bottom: 12px;" >
      <el-button :icon="Plus" type="primary" @click="${prefix}Add">新增</el-button>
      <el-button :icon="Edit" type="success" :disabled="${prefix}SelectionList.length !== 1" @click="${prefix}Update()">编辑
      </el-button>
      <el-button :icon="Delete" type="danger" :disabled="!(${prefix}SelectionList.length >= 1)" @click="${prefix}Del()">删除
      </el-button>
    </div>`);
  }
  addVariables(tableData.options.dataKey, []);
  addVariables(`${prefix}SelectionList`, []);
  addFunction(`const ${prefix}SelectionChange = (e)=>{
  ${prefix}SelectionList.value = e;
  }`);
  addFunction(`
  const ${prefix}Update = (scope) =>{
  if(!scope){
  ${prefix}OperationForm.value = ${prefix}SelectionList.value[0];
  }else{
  ${prefix}OperationForm.value = scope.row;
  }
  ${prefix}OperationFormVisible.value = true;
  }
  `);
  addFunction(`
  const ${prefix}Add = ()=>{
  ${prefix}OperationForm.value = {}
  ${prefix}OperationFormVisible.value = true;
  }
  `);
  addFunction(`

const ${prefix}Del = () => {
  ElMessageBox.confirm(
    '确定删除这些数据吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      beforeClose: async (action, instance, done) => {
        try {
  let localData = pageData.value;
        let formData = { ${tableData.options.delField}: ${prefix}SelectionList.value.map(v => v[${tableData.options.delField}]) }
        ${tableData.options.deleteFunction}
          done();
        } catch (e) {
          console.log(e);
        }
      }
    }
  )
    .then(async () => {
      ElMessage({
        type: 'success',
        message: '删除完成'
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      });
    });
};
  `);
  addCode(`
    <el-table :data="formData['${tableData.options.dataKey}']"
              style="width: 100%"
              @selection-change="${prefix}SelectionChange">
      <el-table-column type="selection" width="55" />
      ${tableData.options.thTdMap.map(i => {
    return `<el-table-column prop="${i.key}" label="${i.name}"  />`;
  }).join('\n')}
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click.prevent="${prefix}Update(scope)"
          >
            修改
          </el-button>
              <el-button
                link
                type="primary"
                size="small"
            @click.prevent="${prefix}Del(scope)"
              >
                删除
              </el-button>
        </template>
      </el-table-column>
    </el-table>
`);
  if (isForm) {
    addCode(`</el-form-item>`);
  } else {

  }
  if (true) {
    addVariables(`${prefix}OperationFormVisible`, false);
    addVariables(`${prefix}OperationTitle`, '');
    addFormVariables([], `${prefix}OperationForm`, {});
    addCode(`
        <el-dialog v-model="${prefix}OperationFormVisible" :title="${prefix}OperationTitle" width="500">
      <el-form :model="${prefix}OperationForm" label-width="120px">`);

    tableData.options.thTdMap.filter(e => e.isUpdate).map(e => {
      const noFun = () => {
      };
      (elementEnum[e.type] || noFun)({
        isForm: true,
        formData: { options: { key: `${prefix}OperationForm` } },
        elementData: { options: e },
        tier: [`${prefix}OperationForm`]
      });
    });
    addCode(`
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="${prefix}OperationFormVisible = false;${prefix}OperationForm={}">关闭</el-button>
          <el-button type="primary" @click="${prefix}AddSubmit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
    `);
    addFunction(`
    const ${prefix}AddSubmit = async ()=>{
    let formData = ${prefix}OperationForm.value
    let localData = pageData.value
    ${tableData.options.updateFunction}
    ${prefix}OperationFormVisible.value = false
    }
    `);
  }

};

export {
  getTableCode
};
