import { show } from "@/api/system/customForm";
import { listCommondepartment, listCommonuser } from "@/api/common";
import { primaryColor } from "@/styles/variables.scss"
import { download } from "@/utils/downloadRequest";

function down (url) {
  download(url)
}
function preview (url) {
  let codeUri = `${process.env.VUE_APP_PREVIEW_API}?url=${encodeURIComponent(
    new Buffer(url).toString("base64")
  )}`

  window.open(codeUri,'_blank')
}

const baseTable = new Map([
  ['departments', async () => {
    return (await listCommondepartment())
  }],
  ['admins',async () => {
    return (await listCommonuser())
  }]
])
export async function getForm (customFormId) {
  let selectItemMap = new Map();
  if (!customFormId) {
    console.warn("customFormId is required!")
    return
  }
  const res = await show({ id: customFormId }, false);

  const { fields, relation } = res;

  let fieldRes = fields.sort((a,b) => a.sort - b.sort);

  if (
    !fields ||
    !relation ||
    !fields instanceof Array ||
    !relation instanceof Array
  ) {
    throw new Error("fields或relation参数错误");
  }

  fieldRes?.forEach((i, index) => {
    i._relations = relation.find((j) => j.custom_form_field === i.field);
    if (i.select_item && typeof i.select_item === 'object') {
      let keys = Object.keys(i.select_item)
      if (keys.length > 0) {
        i._params = keys.map((key) => {
          return {
            key,
            value: /^\d*$/.test(i.select_item[key])
              ? Number(i.select_item[key])
              : i.select_item[key],
          };
        });

        selectItemMap.set(i.field, i._params);

        //有select,radio
        i.edit_input = 'radio'
      }
    }
  })

  return { fieldRes, selectItemMap };
}

export function getRenderTable (ctx, fields, replaces) {
  const h = ctx.$createElement;
  if (replaces && !(replaces instanceof Map)) {
    throw new Error("replaces参数错误,需要Map类型");
  }
  return fields.map((field, index) => {
    console.log("fields",fields)
    //

    //自定义替换
    if (replaces instanceof Map && replaces.get(field.field)) {
      return replaces.get(field.field)
    }
    //文件
    if (field.edit_input === 'file' || field.edit_input === 'files') {
      let renderFn = () => {}
      const { link_relation, foreign_key, link_with_name } = field._relations;
      if (link_relation === 'hasOne' || link_relation === 'newHasOne') {
        renderFn = row => {
          if (!row[link_with_name]?.url) {
            return ''
          }
          return (
            <div style="display: flex;align-items: center;">
              {
                ['jpg','jpeg','png','gif','svg','webp','bmp'].indexOf(row[link_with_name]?.extension) === -1 ?
                  (<el-link
                    type="primary"
                    download={row[link_with_name]?.original_name}
                  >
                    {row[link_with_name]?.original_name}
                  </el-link>) : (<el-image fit="contain" style="max-width: 80px;max-height: 60px;" src={row[link_with_name]?.url} alt={row[link_with_name]?.original_name} preview-src-list={[row[link_with_name]?.url]}></el-image>)
              }

              <Icon type="md-cloud-download"
                    style="margin-left: 10px;cursor: pointer;font-size: 17px;"
                    color={primaryColor}
                    on={{
                      ['click']: _ => down(row[link_with_name]?.url)
                    }}/>
              <Icon type="md-eye"
                    style="margin-left: 4px;cursor: pointer;font-size: 17px;"
                    color={primaryColor}
                    on={{
                      ['click']: _ => preview(row[link_with_name]?.url)
                    }}/>
            </div>
          )
        }
      } else {
        renderFn = row => (
          <div style="display: flex;flex-direction: column;align-items: flex-start;">
            {row[link_with_name]?.map((o,oi) => (
              <div style="display: flex;align-items: center;">
                {
                  ['jpg','jpeg','png','gif','svg','webp','bmp'].indexOf(o?.extension) === -1 ?
                    (<el-link type="primary" download={o?.original_name} href={o?.url}>
                      {oi+1}. { o?.original_name || o?.name }
                    </el-link>) : (<el-image fit="contain" style="max-width: 80px;" src={o?.url} alt={o?.original_name} preview-src-list={[o?.url]}></el-image>)
                }

                <Icon type="md-cloud-download"
                      style="margin-left: 10px;cursor: pointer;font-size: 17px;"
                      color={primaryColor}
                      on={{
                        ['click']: _ => down(o?.url)
                      }}/>
                <Icon type="md-eye"
                      style="margin-left: 4px;cursor: pointer;font-size: 17px;"
                      color={primaryColor}
                      on={{
                        ['click']: _ => preview(o?.url)
                      }}/>
              </div>
            ))}
          </div>
        )
      }

      return {
        prop: field.field,
        label: field.name,
        width: field.width,
        align: "left",
        showOverflowTooltip: false,
        customFn: row => renderFn(row)
      }
    }

    //关联
    if (field._relations && typeof field._relations === 'object') {
      let renderFn = () => {}
      const { link_relation, foreign_key, link_with_name } = field._relations;
      if (link_relation === 'hasOne' || link_relation === 'newHasOne') {
        renderFn = row => (
          <span>
            {row[link_with_name]?.name ||
              row[link_with_name]?.title ||
              row[link_with_name]?.no ||
              row[link_with_name]?.value ||
              row[link_with_name]?.biaoti ||
              row[link_with_name]?.mingcheng}
          </span>
        )
      }
      if (link_relation === 'hasMany' || link_relation === 'newHasMany') {
        renderFn = row => (
          <div>
            {row[link_with_name]?.map((o) => (
              <p>
                {o?.name ||
                  o?.title ||
                  o?.no ||
                  o?.value ||
                  o?.biaoti ||
                  o?.mingcheng}
              </p>
            ))}
          </div>
        )
      }

      return {
        prop: field.field,
        label: field.name,
        width: field.width,
        customFn: row => renderFn(row),
        fixed: field.is_fixed
      }
    }

    //富文本
    if (field.edit_input === 'richtext') {
      return {
        prop: field.field,
        label: field.name,
        width: field.width,
        showOverflowTooltip: false,
        customFn: row => (
          <el-popover placement="bottom" trigger="click" width={row[field.field] ? 400 : 100}>
            {
              row[field.field] ? <div slot="default" style="width: 100%;max-height: 200px;overflow: scroll;" domPropsInnerHTML={row[field.field]}></div> : <div slot='default' style='text-align: center'>暂无内容</div>
            }

            <el-link type="primary" slot="reference">查看</el-link>
          </el-popover>
        ),
        fixed: field.is_fixed
      }
    }

    //select内容
    if (
      field._params && field._params instanceof Array
    ) {

      return {
        prop: field.field,
        label: field.name,
        width: field.width,
        customFn: row => (
          <span>{ field._params.find(param => param.value == row[field.field])?.key }</span>
        ),
        fixed: field.is_fixed
      }
    }

    if(field.list_show===0){

    }else{
      return {
        prop: field.field,
        label: field.name,
        width: field.width,
        fixed: field.is_fixed
      }
    }

  })
}
