<template>
  <el-dialog
    :title="formTitle"
    v-if="displayDialog.newDialog"
    :visible="true"
    :fullscreen="true"
    :append-to-body="false"
    :modal="false"
    :modal-append-to-body="false"
    :show-close="false"
  >
    <div id="stepsForm">
      <el-steps
        :active="active"
        process-status="finish"
        finish-status="success"
        :align-center="true"
      >
        <el-step
          v-for="(item, index) in stepFilters"
          :key="index"
          :title="item"
        ></el-step>
      </el-steps>
      <!-- 总体信息 -->
      <curren-Form
        v-if="active == 0"
        class="page1"
        size="medium"
        ref="page1"
        :searchData="CreateFormData"
        :searchForm="CreateForm"
        :searchOptions="Options"
        :searchHandle="editHandle"
        :rules="Rules"
        :loading="loading"
        @push="DataPush(arguments)"
        @submitForm="editFormClick(arguments)"
      >
      </curren-Form>
      <!-- 库位参数 -->
      <!-- 搜索按钮——窗体组件 -->
      <searchPage
        ref="searchTable"
        :tableLoading="tableLoading"
        :advancedFilter="advancedFilter(
            'basedata/location',
            pageListLocation,
            'totalCountLocation',
            'locationData',
            oldSkipCountLocation
          )"
        :setUTableHeight="330"
        :filterPageListParams="[]"
        :formTitle="''"
        :displayDialog="active == 1"
        :selectionTable="false"
        :editHandle="editHandle"
        :searchTableData="locationData"
        :searchTableColumns="$isTableColumns.Location"
        :searchTotalCount="totalCountLocation"
        :supplierItemPage="pageListLocation"
        @SizeChange="AddNewAlterResultCount(
            $event,
            'basedata/location',
            pageListLocation,
            'totalCountLocation',
            'locationData',
            oldSkipCountLocation
          )"
        @CurrentChange="AddNewAlertoldSkipCount(
            $event,
            'basedata/location',
            pageListLocation,
            'totalCountLocation',
            'locationData',
            oldSkipCountLocation
          )"
        @tableButtonClick="addFormData(arguments)"
      ></searchPage>
      <!-- 其他参数 -->
      <curren-Form
        v-loading="loading"
        v-if="active == 2"
        class="page1"
        size="medium"
        ref="page1"
        :searchData="other"
        :searchForm="otherForm"
        :searchOptions="Options"
        :searchHandle="editHandle"
        :rules="Rules"
        :loading="loading"
        @push="DataPush(arguments)"
        @submitForm="editFormClick(arguments)"
      >
      </curren-Form>
      <!-- <curren-Form
        v-if="active === 4"
        size="medium"
        class="page3"
        :searchData="previewFormData"
        :searchForm="CreateForm | formData"
        :searchHandle="editHandle"
        :rules="Rules"
        :loading="loading"
        @submitForm="editFormClick(arguments)"
      >
        <template>
          <el-form-item class="formTable-box" prop="details">
            <currenTable
              :tableData="previewFormData.details"
              :tableColumns="detailsTableColumns | formDataDetails"
              :selectionTable="false"
            >
            </currenTable>
          </el-form-item>
        </template>
      </curren-Form> -->
      <div
        v-if="active === step.length - 1 && pageStatus === 'success'"
        class="page4"
      >
        <el-result icon="success" title="成功提示" subTitle="新增成功">
          <template slot="extra">
            <!-- <el-button type="primary" size="medium" @click="tuoFormPrint"
              >打印托标签</el-button
            >
            <el-button type="primary" size="medium" @click="xbqFormPrint"
              >打印箱标签</el-button
            > -->
            <el-button
              v-for="item in successHandle"
              :key="item.label"
              :type="item.type"
              size="medium"
              @click="item.click()"
              >{{ item.label }}</el-button
            >
            <el-button type="primary" size="medium" @click="close(1)"
              >退出</el-button
            >
          </template>
        </el-result>
      </div>
      <div
        v-if="active === step.length - 1 && pageStatus === 'error'"
        class="page4"
      >
        <el-result icon="error" title="错误提示" subTitle="新增失败">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="close(1)"
              >退出</el-button
            >
          </template>
        </el-result>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import currenForm from "@/components/currenForm";
import currenTable from "@/components/currenTable";
import {
  getPageList,
  postCreateWithCondition,
  postCreate,
} from "@/api/wms-api";
export default {
  name: "stepsForm",
  components: {
    currenForm,
    currenTable,
  },
  watch: {
    active(val) {
      if (val != 0) {
        this.editHandle[0].label = "上一步";
      } else {
        this.editHandle[0].label = "取消";
      }
    },
  },
  filters: {
    formData(val) {
      let data = JSON.parse(JSON.stringify(val));
      val.forEach((key, index) => {
        data[index].disabled = "true";
        delete data[index].focus;
        if (key.type == "autocomplete" || key.type == "import") {
          data[index].type = "input";
        }
      });
      return data;
    },
    formDataDetails(val) {
      let data = JSON.parse(JSON.stringify(val));
      val.forEach((key, index) => {
        data[index].disabled = "true";
        delete data[index].focus;
        delete data[index].rules;
        if (key.type == "autocomplete" || key.type == "import") {
          data[index].type = "input";
        } else if (key.type == "objectAutocomplete") {
          data[index].type = "objectInput";
        } else if (key.prop == "containerCode") data[index].disabled = "false";
      });
      return data;
    },
  },
  props: {
    //名称
    formTitle: {
      type: String,
      default: "",
    },
    //是否弹窗
    displayDialog: {
      type: Object,
      default: () => {
        return {
          newDialog: false,
        };
      },
    },
    //主表提交数据
    CreateFormData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //主表显示form
    CreateForm: {
      type: Array,
      default: () => {
        return [];
      },
    },
    //预览数据
    // previewFormData: {
    //   type: Object,
    //   default: () => {
    //     return {}
    //   }
    // },
    //检验
    Rules: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //下拉选择
    Options: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //子表table显示
    detailsTableColumns: {
      type: Array,
      default: () => {
        return [];
      },
    },
    //子表提交数据
    childTableData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    //成功后的操作
    successHandle: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  computed: {
    stepFilters() {
      let stepFilters = [];
      const routeName = this.$route.meta.title;
      this.step.forEach((key) => {
        stepFilters.push(routeName.concat(key));
      });
      return stepFilters;
    },
    // autoAdvanced () {
    //     if (this.active == 1) {
    //       return this.advancedFilter(
    //         'item-basic',
    //         this.pageListItemBasic,
    //         'totalCountItemBasic',
    //         'itemBasicData',
    //         this.oldSkipCountItemBasic
    //       )
    //     } else if (this.active == 2) {
    //       return this.advancedFilter(
    //         'location',
    //         this.pageListLocation,
    //         'totalCountLocation',
    //         'locationData',
    //         this.oldSkipCountLocation
    //       )
    //     }
    // },
  },
  data() {
    return {
      active: 0,
      formReveal: 1,
      pageStatus: "",
      filterListParams: [],
      itemBasicData: [],
      isItemBasicData: [],
      previewFormData: [],
      totalCountItemBasic: 0,
      oldSkipCountItemBasic: 1,
      pageListItemBasic: {
        condition: {
          filters: [],
        },
        Sorting: "",
        SkipCount: 0,
        MaxResultCount: 100,
      },
      locationData: [],
      isLocationData: [],
      totalCountLocation: 0,
      oldSkipCountLocation: 1,
      pageListLocation: {
        condition: {
          filters: [],
        },
        Sorting: "",
        SkipCount: 0,
        MaxResultCount: 100,
      },
      other: {
        otherParam: [],
      },
      otherForm: [
        {
          label: "状态",
          prop: "otherParam",
          type: "checkbox",
          indeterminate:"true",
          checkboxs: "radios",
        },
      ],
      otherFormData: {
        countMethod: 0,
        // type: 0,//盘点类型
        company: null,
        description: null,
        // beginTime: null,
        // endTime: null,
        planTime: null,
        partCondition: {},
        locCondition: {},
        statusList: [],
        worker: null,
        warehouseCode: null,
        remark: null,
        requestType: null,
      },
      loading: false,
      tableLoading: false,
      session: null,
      // step: ["总体信息", "物品参数", "库位参数", "其他参数", "结果"],
      step: ["总体信息", "库位参数", "其他参数", "结果"],
      editHandle: [
        { label: "取消", name: "cancel" },
        { label: "下一步", type: "primary", name: "determine" },
      ],
    };
  },
  mounted() {
    this.session = JSON.parse(JSON.stringify(this.CreateFormData));
  },
  methods: {
    //结束退出
    close(val) {
      this.active = 0;
      const filter ={
        condition: {
          filters: [],
        },
        Sorting: "",
        SkipCount: 0,
        MaxResultCount: 100,
      }
      this.pageListItemBasic = JSON.parse(JSON.stringify(filter))
      this.pageListLocation = JSON.parse(JSON.stringify(filter))
      const data = JSON.parse(JSON.stringify(this.session));
      this.itemBasicData = []
      this.locationData = []
      this.$emit("close", data, val);
    },
    //autoComplete主表
    DataPush(val) {
      this.$emit("DataPush", val);
    },
    //autoComplete子表
    detailsDataPush(val) {
      this.$emit("detailsDataPush", val);
    },
    //确定筛选
    advancedFilter(url, list, TotalCount, data, oldSkipCount) {
      return () => {
        // 盘点库存 过滤线边仓数据 20230417
        if (data == 'locationData') {
          list.condition.filters.push({
            action: "!=",
            column: "type",
            logic: "And",
            value: "5"
          })
        }
        list.SkipCount = (oldSkipCount - 1) * list.MaxResultCount;
        this.tableLoading = true;
        getPageList(list, url)
          .then((res) => {
            this[data] = res.items;
            this[TotalCount] = res.totalCount;
            this.tableLoading = false;
          })
          .catch(() => {
            this.tableLoading = false;
          });
      };
    },
    //选择子表(接收分页组件emit改变每页最大页数)
    AddNewAlterResultCount(val, url, list, TotalCount, data, oldSkipCount) {
      list.MaxResultCount = val;
      const Function = this.advancedFilter(
        url,
        list,
        TotalCount,
        data,
        oldSkipCount
      );
      Function();
    },
    //选择子表(接收分页组件emit改变当前页)
    AddNewAlertoldSkipCount(val, url, list, TotalCount, data, oldSkipCount) {
      oldSkipCount = val;
      const Function = this.advancedFilter(
        url,
        list,
        TotalCount,
        data,
        oldSkipCount
      );
      Function();
    },
    //打印托标签
    tuoFormPrint() {
      this.$emit("tuoFormPrint");
    },
    //打印箱标签
    xbqFormPrint() {
      this.$emit("xbqFormPrint");
    },
    // //添加封装
    // addNew (url, list, TotalCount, data, MaxResultItem) {
    //   list.SkipCount = 0
    //   list.MaxResultCount = JSON.parse(TotalCount)
    //   getPageList(list, url).then((res) => {
    //     this[data] = res.items
    //     list.MaxResultCount = MaxResultItem
    //   })
    // },
    //添加明细（上一步）
    addFormData(val) {
      if (val[0] == "cancel") {
        this.active--;
      } else {
        // 物品参数
        // if (this.active == 1) {
        //   const MaxResultItem = JSON.parse(
        //     this.pageListItemBasic.MaxResultCount
        //   );
        //   //   this.addNew('item-basic', this.pageListItemBasic, this.totalCountItemBasic, 'isItemBasicData', MaxResultItem)
        //   //   this.pageListItemBasic.MaxResultCount = MaxResultItem
        //   const Function = this.advancedFilter(
        //     "basedata/location",
        //     this.pageListLocation,
        //     "totalCountLocation",
        //     "locationData",
        //     this.oldSkipCountLocation
        //   );
        //     Function();
        //   this.$nextTick(()=>{
        //     this.active++;
        //   })
        // }
        // 库位参数
        if (this.active == 1) {
          const MaxResultLocation = JSON.parse(
            this.pageListLocation.MaxResultCount
          );
          //   this.addNew('location', this.pageListLocation, this.totalCountLocation, 'isLocationData', MaxResultLocation)
          //   this.pageListLocation.MaxResultCount = MaxResultLocation
          this.active++;
        }
      }
    },
    //拆分
    splitFormData(val) {
      return new Promise((resolve, reject) => {
        postCreateWithCondition(val, "wms/store/count-plan")
          .then((res) => {
            this.previewFormData = JSON.parse(
              JSON.stringify(this.CreateFormData)
            );
            //   delete this.previewFormData.details
            this.$listAssign(this.previewFormData, res);
            this.previewFormData.details = [];
            res.details.forEach((item) => {
              const details = JSON.parse(
                JSON.stringify(...this.childTableData)
              );
              this.$listAssign(details, item);
              this.previewFormData.details.push(details);
            });
            resolve();
          })
          .catch((err) => {
            reject();
          });
      });
    },
    // 下一步
    editFormClick(val) {
      //   Moment(this.CreateFormData.arriveTime).format()
      if (val[0] == 0) {
        if (this.active == 0) {
          this.close(0);
        } else {
          this.active--;
        }
      } else {
        val[1].validate((valid) => {
          if (valid) {
            // 总体信息
            if (this.active == 0) {
              const Function = this.advancedFilter(
                // "basedata/item-basic",
                // this.pageListItemBasic,
                // "totalCountItemBasic",
                // "itemBasicData",
                // this.oldSkipCountItemBasic
                 'basedata/location',
                  this.pageListLocation,
                  'totalCountLocation',
                  'locationData',
                  this.oldSkipCountLocation
              );
              Function();
              this.active++;
            } 
            // 其他参数
            else if (this.active == 2) {
              this.$listAssign(this.otherFormData, this.CreateFormData);
              this.otherFormData.partCondition =
                this.pageListItemBasic.condition;
              this.otherFormData.locCondition = this.pageListLocation.condition;
              this.otherFormData.statusList = [];
              let checkboxArray = []
              this.other.otherParam.forEach(item => {
                if (item == '待检') {
                  checkboxArray.push(1)
                } else if (item == '合格') {
                  checkboxArray.push(2)
                } else if (item == '不合格') {
                  checkboxArray.push(3)
                } else if (item == '隔离') {
                  checkboxArray.push(4)
                } else if (item == '破坏') {
                  checkboxArray.push(5)
                } else if (item == '冻结') {
                  checkboxArray.push(6)
                }
              })
              // 待检', '合格', '不合格', '隔离', '破坏', '冻结'
              this.otherFormData.statusList = checkboxArray;
              this.otherFormData.vendCondition = {
                filters:[]
              }
              this.loading = true;
              // this.otherFormData.requestType = 2
              this.splitFormData(this.otherFormData).then(
                (resolve) => {
                  this.pageStatus = "success";
                  this.active++;
                  this.loading = false;
                },
                (reject) => {
                  this.pageStatus = "error";
                  this.active++;
                  this.loading = false;
                }
              );
            }
            //  else if (this.active == 4) {
            //   postCreate(this.previewFormData, 'count-plan').then(res => {
            //     this.pageStatus = 'success'
            //     this.active++
            //     this.loading = false
            //   }).catch(err => {
            //     this.pageStatus = 'error'
            //     this.active++
            //     this.loading = false
            //   })
            // }
            else {
              this.$errorMsg("请检查表单");
            }
          }
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./style/index.scss";
</style>
<style lang="scss">
#stepsForm{
  .formButton{
    text-align: right;
  }
  .searchPageComponents{
    top: 130px !important;
  }
  .el-dialog__wrapper{
    height: unset;
  }
}
</style>