<template>
  <div>
    <vxe-modal
      :z-index="zIndex"
      :value="isShow"
      show-footer
      title="导出"
      show-confirm-button
      :width="defaultModalSize.width"
      :height="defaultModalSize.height"
      esc-closable
      transfer
      :fullscreen="$store.getters.device === 'mobile'"
      @input="e => $emit('update:isShow',e)"
    >
      <div>
        <h4>当前导出流程： {{ config.name }}</h4>

        <h4 style="display: inline-block;">导出文件名：</h4>
        <el-input style="max-width: 220px;" size="small" v-model="fileName"></el-input>
        <el-button style="margin-left: 10px;" type="primary" size="small" icon="el-icon-download" @click="confirm">导出</el-button>
        <h4>需要导出字段：</h4>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="selectedFields" @change="handleCheckedFieldsChange">
          <el-checkbox v-for="field in mainFields" :label="field.name" :key="field.id">{{ field.label }}</el-checkbox>
        </el-checkbox-group>

        <template v-if="sub2ModelFields.length>0">
          <h4>存在子表单</h4>
          <el-checkbox :indeterminate="isIndeterminate2" v-model="checkAll2" @change="handleCheckAllChange2">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="selectedFields2" @change="handleCheckedFieldsChange2">
            <el-checkbox v-for="(field,index) in sub2ModelFields" :label="field.name" :key="index">{{ field.label }}</el-checkbox>
          </el-checkbox-group>
        </template>


        <!-- <div v-for="(field,index) in sub2ModelFields" :key="index" style="padding-left: 10px;">
          <h5>{{ field }}</h5>

        </div> -->
      </div>
    </vxe-modal>
  </div>
</template>

<script>
import {fieldConfig} from "@/api/flow"
import {defaultModalSize} from "@/settings";
import {PopupManager} from "element-ui/lib/utils/popup";
import {download} from "@/utils/downloadRequest"

export default {
  props: {
    isShow: {
      type: Boolean,
      default: false,
      required: true
    },
    select: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      zIndex: PopupManager.nextZIndex(),
      defaultModalSize,
      loading: false,
      config: {
        fields: []
      },
      sub2ModelFields:[],
      fileName: `导出_${this.$moment().valueOf()}`,
      selectedFields: [],
      checkAll: false,
      isIndeterminate: false,
      //子表单
      selectedFields2: [],
      checkAll2: false,
      isIndeterminate2: false,
    }
  },
  computed: {
    mainFields() {
      return this.config?.fields?.filter(i => i.type !== 'relation' && i.type !== 'file')
    },
    relationsFields() {
      return this.config?.fields?.filter(i => i.type === 'relation')
    }
  },
  methods: {
    handleCheckedFieldsChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.mainFields?.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.config?.fields?.length;
    },
    handleCheckAllChange(val) {
      this.selectedFields = val ? this.mainFields?.map(i => i.name) : [];
      this.isIndeterminate = false;
    },

    handleCheckedFieldsChange2(value) {
      let checkedCount = value.length;
      this.checkAll2 = checkedCount === this.sub2ModelFields.length;
      this.isIndeterminate2 = checkedCount > 0 && checkedCount < this.sub2ModelFields.length;
    },
    handleCheckAllChange2(val) {
      this.selectedFields2 = val ? this.sub2ModelFields?.map(i => i.name) : [];
      this.isIndeterminate2 = false;
    },
    async getFields(id) {
      try {
        const { customModel } = await fieldConfig(id)
        this.config = customModel
        this.config.fields.forEach(i => {
          i.name = i.name
        })
        this.fileName = `${customModel.name}_${this.$moment().valueOf()}`
      } catch (err) {
        console.error(id)
      }
    },

    async confirm() {
      // 自定义 paramsSerializer 函数
      const paramsSerializer = (params) => {
        const parts = [];

        // 递归处理嵌套对象
        const serialize = (obj, parentKey) => {
          for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
              const value = obj[key];
              const fullKey = parentKey ? `${parentKey}[${key}]` : key;

              if (value && typeof value === 'object' && !Array.isArray(value)) {
                // 如果是嵌套对象，递归处理
                serialize(value, fullKey);
              } else if (Array.isArray(value)) {
                // 如果是数组，遍历数组并处理每个元素
                value.forEach((item, index) => {
                  if (item && typeof item === 'object') {
                    // 如果数组元素是对象，递归处理
                    serialize(item, `${fullKey}[${index}]`);
                  } else {
                    // 如果数组元素是普通值，直接序列化
                    parts.push(`${encodeURIComponent(`${fullKey}[${index}]`)}=${encodeURIComponent(item)}`);
                  }
                });
              } else {
                // 如果是普通键值对，直接序列化
                parts.push(`${encodeURIComponent(fullKey)}=${encodeURIComponent(value)}`);
              }
            }
          }
        };

        // 开始序列化
        serialize(params, '');

        // 将部分拼接为查询字符串
        return parts.join('&');
      };
      try {
        let export_fields = {
          'no':'编号',
          'status_text':'状态',
          'creator.name':'发起人',
        }
        // 一般采购
        if(this.select.custom_model_id==99){
          export_fields['undertake_name'] = '承办人'
          export_fields['apply_money'] = '已申请金额'
          export_fields['out_contract_money'] = '金额'
        }
        if((this.selectedFields && this.selectedFields.length>0) || (this.selectedFields2 && this.selectedFields2.length>0)){
          this.selectedFields?.forEach(field => {
            let key = field
            export_fields[key] = this.config?.fields?.find(j => j.name === key)?.label
          })
          if(this.selectedFields2 && this.selectedFields2.length>0){
            this.selectedFields2?.forEach(field => {
              let key = field
              export_fields[key] = this.sub2ModelFields?.find(j => j.name === key)?.label
            })
          }

          await download(`/api/oa/flow/list/${this.$route.params.type}`, 'get', {
            ...this.select,
            type: this.$route.params.type,
            is_export: 1,
            export_name: this.fileName,
            export_fields
          }, this.fileName+'.xlsx', paramsSerializer)
        }else{
          // this.$Message.warning("请选择需要导出的字段")
          return
        }

      } catch (err) {
        console.error(err)
      }
    }
  },
  watch: {
    isShow(newVal) {
      if(newVal) {
        this.zIndex = PopupManager.nextZIndex()
      }
    },
    "select.custom_model_id"(newVal) {
        // this.getFields(newVal)
    }
  },
}
</script>

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