<template>
  <div class="box-padding">
    <pi-search :formConfig="formConfig" v-model="formInline" @piSearchEvent="orderSearch" @piResetEvent="orderSearch" @toggle="toggle"></pi-search>
    <el-row>
      <el-button plain size="small" type="primary" @click="delBtn()" class="btnleft">删除</el-button>
      <el-button plain size="small" type="primary" @click="saveInvoiceBtn()" class="btnleft">保存</el-button>
      <el-button plain size="small" type="primary" @click="SAPReadingBeforeFn" class="btnleft">订单读入</el-button>
    </el-row>
    <custom-table :columns="tableColumn" :data="tableList" :default-sort="{prop: 'ddcjsj', order: 'descending'}" @selection-change="handleSelectChange" ref='CustomTable' :height='tableHeight'></custom-table>
    <Pagination :total="page.totalCount" :page="page.page" :limit="page.limit" @pagination="pageChange"></Pagination>
    <el-dialog title="订单读入" :visible.sync="SAPReadingShow" class="SAPdialog" center width="750px">
      <el-form ref='SAPReadingFormData' :model="ReadingData" label-width="110px" label-position="right">
        <el-row :gutter="12">

          <el-col :span="12">
            <el-form-item label='凭证号:'>
              <el-input v-model="ReadingData.pzh" placeholder="请输入凭证号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label='发货单号:'>
              <el-input v-model="ReadingData.ddh" placeholder="请输入发货单号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label='订单时间：'>
              <el-date-picker v-model="ReadingData.date" :clearable="false" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button plain size="small" type="primary" @click="ReadingSubmitFn">读入</el-button>
        <el-button plain size="small" @click="SAPReadingShow=false">取消</el-button>
      </span>
    </el-dialog>

    <deleteModel v-if="modelFrom.Show" :deleteVisible="modelFrom.Show" :tip="modelFrom.Tip" @click-cancel="deleteBtncancel" @click-sure="deleteBtn" />

    <el-dialog title="提示" :visible.sync="savaShow" center width="650px">
      <div class="savaShowCss">
        <div class="dev" v-for="(item,index) in savaData" :key="index">{{index + 1 + '、'+ item }}</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button plain size="small" type="primary" @click="savaShow=false">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import common from "@common/utils/common";
import { showLoading, hideLoading } from "@common/utils/loading";
import setting from "@common/mixins/setting";
import { convertInvoiceTypeApi, sapOrderList, readIn, orderExtractApi, deleteByIdsApi } from "@common/http/orderApiUrl";
import fpdmListEnum from '@/common/utils/fpdmListEnum'

export default {
  mixins: [setting],
  data () {
    return {
      searchIsShow: false,
      SAPReadingShow: false,
      ReadingData: {
        date: [],
        ddh:'',
        pzh:''
      },
      savaShow: false,
      savaData: [],
      //删除模态框
      modelFrom: {
        Show: false,
        Tip: ''
      },
      spaPickerOptions: {
        disabledDate: (time) => {
          return time > Date.now() || time.getTime() < new Date(JSON.stringify(new Date().getFullYear() - 3))
        }
      },
      changeTypeShow: false,
      changeTypeData: {
        tdysbs: '',
        fplxbs: ''
      },
      fpdmList: Object.freeze(
        [
          {
            label: '数电专用发票',
            value: '001'
          }, {
            label: '数电普通发票',
            value: '002'
          }, {
            label: '数电纸票专用发票',
            value: '085'
          }, {
            label: '数电纸票普通发票',
            value: '086'
          }, {
            label: '增值税专用发票',
            value: '004'
          }, {
            label: '机动车销售统一发票',
            value: '005'
          }, {
            label: '二手车销售统一发票',
            value: '006'
          }, {
            label: '增值税普通发票',
            value: '007'
          }, {
            label: '增值税电子普通发票',
            value: '026'
          }, {
            label: '增值税电子专用发票',
            value: '028'
          }]
      ),
      formConfig: [
        {
          label: "订单号",
          type: "input",
          key: "ddh",
          placeholder: "请输入订单号",
        },
        {
          label: "购方名称",
          type: "input",
          key: "gfmc",
          placeholder: "请输入购方名称",
        },
        {
          type: "select",
          label: "发票类型",
          key: "invoiceType",
          placeholder: "全部",
          showAll: true,
          props: {
            value: "value",
            label: "label",
          },
          optionsKey: 'index',
          options: [
            {
              label: '数电专票(电子)',
              value: 'Z'
            }, {
              label: '数电普票(电子)',
              value: 'P'
            }]
        },
        {
          label: "凭证号",
          type: "input",
          key: "pzh",
          placeholder: "请输入凭证号",
        },
        {
          label: "订单读入时间",
          key: "time",
          type: "date",
          isHide: false,
          subtype: "date",
          value: "",
          valueFormat: "yyyy-MM-dd",
          placeholder: "开始时间",
          editable: false,
          clearable: false,
          brothers: {
            editable: false,
            clearable: false,
            valueFormat: "yyyy-MM-dd",
            key: "time",
            type: "date",
            isHide: false,
            subtype: "date",
            placeholder: "结束时间"
          },
        },
        {
          label: "订单时间",
          key: "time1",
          type: "date",
          isHide: false,
          subtype: "date",
          value: "",
          valueFormat: "yyyy-MM-dd",
          placeholder: "开始时间",
          editable: false,
          clearable: false,
          brothers: {
            editable: false,
            clearable: false,
            valueFormat: "yyyy-MM-dd",
            key: "time1",
            type: "date",
            isHide: false,
            subtype: "date",
            placeholder: "结束时间"
          },
        },
      ],
      formInline: {
        time: [],
        time1: [],
        ddh: '',
        gfmc: '',
        invoiceType: '',
        pzh:'',
        enterpriseNumbers: "", // "企业编号",
        nsrsbh: "", // "纳税人识别号",
        // "pageSize": "每页数量",
        // "currPage": "当前页码"
      },
      tableList: [],
      // orgSpaArrCode: [],
      dplxList: [{
        label: "数电普票(电子)",
        code: "002",
      }, {
        label: "数电专票(电子)",
        code: " 001",
      }],
      page: {
        totalCount: null,
        page: 1,
        limit: 10,
      },
      tableColumn: [
        {
          type: "selection",
          width: "40",
          fixed: "left",
        },
        { label: "序号", type: "index", width: "50", fixed: "left" },

        {
          prop: 'cpznum',
          label: "凭证号",
          width: "120"
        },
        {
          prop: 'cdlcode',
          label: "订单号",
          width: "120"
        },
        {
          prop: 'ccusname',
          label: "购方名称",
          width: "170"
        },
        {
          prop: 'ccusregcode',
          label: "购方税号",
          width: "180"
        },
        {
          prop: 'detailCount',
          label: "行数",
          width: "110"
        },
        {
          label: "发票类型",
          minWidth: "74",
          prop: "cvouchtype",
          render: ({ row }) => {
            let p = (
              <span>
                数电普票(电子)
              </span>
            );
            let z = (
              <span>
                数电专票(电子)
              </span>
            );
            let str = ''
            if (row.cvouchtype === "001") {
              str = z
            } else if (row.cvouchtype === "002") {
              str = p
            } else {
              str = ''
            }
            return str;
          },
        },
        {
          label: "含税金额",
          minWidth: "100",
          prop: "hsje",
          align: "right",
          render: ({ row }) => <span>{common.decimalPrettyValue(row.hsje)}</span>,
        },
        {
          label: "税额",
          minWidth: "100",
          prop: "se",
          align: "right",
          render: ({ row }) => <span>{common.decimalPrettyValue(row.se)}</span>,
        },
        {
          prop: 'cdldate',
          label: "订单日期",
          width: "180"
        },
        {
          prop: 'createTime',
          label: "订单读入时间",
          width: "180"
        },
        {
          label: "操作",
          width: "160",
          fixed: "right",
          render: ({ row }) => {
            let save = (
              <span
                class="common_hover_color common_hover_color_margin"
                onClick={() => this.save(row)}
              >
                保存
              </span>

            );
            let del = (
              <span
                class="common_hover_color common_hover_color_margin"
                onClick={() => this.del(row)}
              >
                删除
              </span>

            );
            let showBtn = [];
            this.buttonCode('common_hover_color') ? showBtn.push(save) : ''
            this.buttonCode('common_hover_color') ? showBtn.push(del) : ''
            return showBtn;
          },
        },
      ],
      multipleSelection: [],
      newDate: "",
      chooseVal: [],
      SyncDisabled: false,
    };
  },
  computed: {
    userInfo: function () {
      return this.$store.state.system.userInfo
    }
  },
  methods: {
    pageChange (cur) {
      this.page.page = cur.page;
      this.page.limit = cur.limit;
      this.orderList();
    },
    // 点击查询时调用的方法
    orderSearch () {
      this.page.page = 1;
      this.orderList();
    },
    //table列表展示数据
    orderList () {
      let invoiceData = {
        ghfNsrsbh: "",
        startTime: this.formInline.time[0] + ' ' + '00:00:00',
        endTime: this.formInline.time[1] + ' ' + '23:59:59',
        readTimeStart: this.formInline.time1[0] + ' ' + '00:00:00',
        readTimeEnd: this.formInline.time1[1] + ' ' + '23:59:59',
        ddh: this.formInline.ddh,
        gfmc: this.formInline.gfmc,
        pzh:this.formInline.pzh,
        invoiceType: this.formInline.invoiceType,
        loginAccount: this.$store.state.system.userInfo.phone,
        orgId: this.$store.state.system.userInfo.dept.enterpriseNumbers,
        entId: this.$store.state.system.userInfo.currentDeptId,
        nsrsbh: this.$store.state.system.userInfo.dept.taxpayerCode, // "纳税人识别号",
        pageSize: this.page.limit, // "每页数量",
        currPage: this.page.page, // "当前页码"
      };
      sapOrderList(invoiceData).then((response) => {
        if (response.code == "0000") {
          response.data.list.map((item) => {
            item.fpdmDesc = fpdmListEnum.get(item.fplxdm)
          })
          this.tableList = response.data.list;
          this.page.totalCount = response.data.total;
        } else {
          this.$message({
            message: response.msg,
            type: "error",
          });
        }
      })
        .catch((error) => {
          this.$message({
            message: error.msg,
            type: "error",
          });
        }).finally(() => {
          hideLoading();
        })
    },
    //SPA读入弹窗打开
    SAPReadingBeforeFn () {
      for (let key in this.ReadingData) {
        this.ReadingData[key] = ''
      }
      this.SAPReadingShow = true;
      this.$nextTick(() => {
        this.$refs.SAPReadingFormData.resetFields();
        console.log(common.formatDate())
        this.$set(this.ReadingData, 'date', common.formatDate());
      })
    },
    ReadingSubmitFn () {
      this.$refs.SAPReadingFormData.validate((valid) => {
        if (valid) {
          showLoading()
          readIn({
            readTimeStart: this.ReadingData.date[0] + ' ' + '00:00:00',
            readTimeEnd: this.ReadingData.date[1] + ' ' + '23:59:59',
            pzh: this.ReadingData.pzh,
            ddh: this.ReadingData.ddh,
            orgId: this.$store.state.system.userInfo.dept.enterpriseNumbers,
            entId: this.$store.state.system.userInfo.currentDeptId,
            nsrsbh: this.$store.state.system.userInfo.dept.taxpayerCode, // "纳税人识别号",
          }).then(res => {
            this.message(res)
          }).finally(() => {
            hideLoading()
          })
        }
      })

    },
    //保存按钮
    saveInvoiceBtn () {
      if (this.chooseVal.length === 0) {
        this.$message({
          message: "请至少选择一条数据",
          type: "error",
        });
      } else {
        let params = {
          entId: this.$store.state.system.userInfo.currentDeptId,
          nsrsbh: this.$store.state.system.userInfo.dept.taxpayerCode, // "纳税人识别号",
          ids: [],
        }
        this.chooseVal.map((item) => {
          params.ids.push(item.id)
        })
        showLoading()
        orderExtractApi(params).then((res) => {
          if (res.code === '0000') {
          if (res.data) {
            this.savaShow = true;
            this.savaData = res.data
            this.orderList()
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }

        } else {
          this.$message.error(res.msg)
        }
        }).finally(() => {
          hideLoading()
        })

      }
    },
    getDefaultDateRange() {
      const endDate = new Date();
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - 7); // 设置开始日期为7天前
      return [
        this.formatDate(startDate),
        this.formatDate(endDate)
      ];
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    save (row) {
      let params = {
        entId: this.$store.state.system.userInfo.currentDeptId,
        nsrsbh: this.$store.state.system.userInfo.dept.taxpayerCode, // "纳税人识别号",
        ids: [row.id],
      }
      showLoading()
      orderExtractApi(params).then((res) => {
        if (res?.code === '0000') {
          if (res.data) {
            this.savaShow = true;
            this.savaData = res.data
            this.orderList()
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }

        } else {
          this.$message.error(res.msg)
        }
      }).finally(() => {
        hideLoading()
      })
    },
    //删除按钮
    delBtn () {
      if (this.chooseVal.length === 0) {
        this.$message({
          message: "请至少选择一条数据",
          type: "error",
        });
      } else {
        this.modelFrom.Show = true;
        this.modelFrom.Tip = '是否确认删除选中数据？'
      }
    },
    deleteBtncancel () {
      this.modelFrom.Show = false
    },
    deleteBtn () {
      let params = {
        ids: [],
        entId: this.$store.state.system.userInfo.currentDeptId,
        nsrsbh: this.$store.state.system.userInfo.dept.taxpayerCode, // "纳税人识别号",
      }
      this.chooseVal.map((item) => {
        params.ids.push(item.id)
      })
      showLoading()
      deleteByIdsApi(params).then((res) => {
        this.message(res)
      }).finally(() => {
        this.modelFrom.Show = false;
        hideLoading()
      })
    },
    del (row) {
      let params = {
        ids: [row.id],
        entId: this.$store.state.system.userInfo.currentDeptId,
        nsrsbh: this.$store.state.system.userInfo.dept.taxpayerCode, // "纳税人识别号",
      }
      showLoading()
      deleteByIdsApi(params).then((res) => {
        if (res?.code === '0000') {
          this.$message({
            dangerouslyUseHTMLString: true,//开启HTML展示
            message: res.msg?.replace(/\n/g, ' <br/> '),//后端返回msg提示JSON格式 /n  替换为 HTML格式 <br/> 展示
            duration: 6000,//两秒自动关闭
            showClose: true,//自定义关闭
            type: "success",
          });
          this.orderList()
        } else {
          this.$message.error(res.msg)
        }
      }).finally(() => {
        this.modelFrom.Show = false;
        hideLoading()
      })
    },
    //接口提示统一处理函数
    message (res) {
      if (res?.code === '0000') {
        this.$message({
          dangerouslyUseHTMLString: true,//开启HTML展示
          message: res.msg?.replace(/\n/g, ' <br/> '),//后端返回msg提示JSON格式 /n  替换为 HTML格式 <br/> 展示
          duration: 6000,//两秒自动关闭
          showClose: true,//自定义关闭
          type: "success",
        });
        this.orderList()
      } else {
        this.$message.error(res.msg)
      }
    },
    getTime (val) {
      return val.replace(/-/g, "");
    },
    //复选框选中数据
    handleSelectChange (val) {
      this.chooseVal = val;
    },
  },
  created () {

      this.formInline.xhfmc = common.defaultXhfNsrsbhIndex.call(this, 'index');
      this.formInline.time = common.formatDate();
      this.formInline.time1 = common.formatDate();
    // this.formInline.generateStatus = '0'
    this.orderList();

  },
  mounted () {
    // let orgArr = this.$store.state.system.userInfo.taxplayercodeDeptList;
    // let list = []
    // if (orgArr.length !== 0) {
    //   orgArr.map((item) => {
    //     if (item.enterpriseNumbers.indexOf("-") !== -1) {
    //       list.push(item.enterpriseNumbers.split("-")[0])
    //     }
    //
    //   })
    // }
    // this.orgSpaArrCode = Array.from(new Set(list))
  }
};
</script>
<style  lang="less" scoped>
.common_mgs_t {
  color: rgb(0, 168, 84);
}
.common_mgs_t:before {
  content: "●";
  color: rgb(0, 168, 84);
}
.common_mgs_f {
  color: rgb(254, 91, 9);
}
.common_mgs_f:before {
  content: "●";
  color: rgb(254, 91, 9);
}
.common_mgs_d:before {
  content: "●";
  color: red;
}
//日期选择器宽度调整
/deep/.el-range-editor.el-input__inner {
  width: 100% !important;
}
/deep/.el-date-editor .el-range-separator {
  width: 10% !important;
}
.SAPdialog {
  /deep/.el-date-editor .el-range-separator {
    line-height: 18px !important;
  }
  /deep/.el-input--suffix .el-input__inner {
    padding-right: 65px !important;
  }
}
.changeTypeStyle {
  /deep/.el-radio-group {
    display: flex;
    margin-top: 12px;
  }
  .colonesty {
    margin-bottom: 10px;
  }
  .elradiosty {
    padding-left: 42px;
  }
}
.savaShowCss {
  text-align: left;

}
</style>
