<template>
  <el-row>
    <el-col :span="24" v-if="show === 1">
      <invoice-head
        :newTime="newTime"
        :oldItem="oldItem"
        :newItem="newItem"
        @nextStep="nextStep"
        :isDetail="false"
        :img="img"
      ></invoice-head>
    </el-col>

    <el-col :span="24" v-else-if="show === 2">
      <el-form
        ref="examForm"
        :model="examForm"
        :rules="examsThis"
        label-width="0px"
        :size="'mini'"
        class="demo-examForm-view"
      >
        <el-row :gutter="10">
          <el-col :span="24">
            <el-row :gutter="20">
              <el-col :span="24" style="padding: 0 20px 0 0">
                <el-table
                  :size="'mini'"
                  :data="examForm.item_list"
                  border
                  style="width: 100%"
                >
                  <el-table-column
                    prop="name"
                    label="货物或应税劳务、服务名称"
                    width="200px"
                  >
                    <template slot-scope="scope">
                      <el-input
                        :size="'mini'"
                        v-model="scope.row.name"
                        placeholder="货物或应税劳务、服务名称"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="specification"
                    label="规格型号"
                    width="150"
                  >
                    <template slot-scope="scope">
                      <el-input
                        :size="'mini'"
                        v-model="scope.row.specification"
                        placeholder="规格型号"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="unit" width="70" label="单位">
                    <template slot-scope="scope">
                      <el-input
                        :size="'mini'"
                        v-model="scope.row.unit"
                        placeholder="单位"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="quantity" width="100" label="数量">
                    <template slot-scope="scope">
                      <el-input
                        :size="'mini'"
                        v-model="scope.row.quantity"
                        placeholder="数量"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="unit_price" label="单价">
                    <template slot-scope="scope">
                      <el-input
                        :size="'mini'"
                        v-model="scope.row.unit_price"
                        placeholder="单价"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="amount" label="金额">
                    <template slot-scope="scope">
                      <el-input
                        :size="'mini'"
                        v-model="scope.row.amount"
                        placeholder="金额"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="tax_rate" width="80" label="税率">
                    <template slot-scope="scope">
                      <el-input
                        :size="'mini'"
                        v-model="scope.row.tax_rate"
                        placeholder="税率"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="tax" label="税额">
                    <template slot-scope="scope">
                      <el-input
                        :size="'mini'"
                        v-model="scope.row.tax"
                        placeholder="税额"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" width="50">
                    <template slot="header" slot-scope="scope">
                      <el-link type="primary" @click="addGoods">新建</el-link>
                      <!-- <el-button size="mini" @click="addGoods">新建</el-button> -->
                    </template>
                    <template slot-scope="scope">
                      <el-tooltip effect="dark" content="删除" placement="top">
                        <i
                          class="el-icon-delete tb-icon"
                          @click="deleteRow(scope.$index)"
                        ></i>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
              <el-col :span="24" style="padding-top: 18px">
                <el-col :span="6"
                  ><el-form-item prop="issue_date">
                    <el-input
                      v-model="examForm.issue_date"
                      placeholder="开票日期"
                    ></el-input> </el-form-item
                ></el-col>
                <el-col :span="6">
                  <el-form-item prop="subtotal_amount">
                    <el-input
                      v-model="examForm.subtotal_amount"
                      placeholder="合计金额"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item prop="subtotal_tax">
                    <el-input
                      v-model="examForm.subtotal_tax"
                      placeholder="合计税额"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item prop="total">
                    <el-input
                      v-model="examForm.total"
                      placeholder="价税合计"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <el-col :span="24" style="text-align: right">
        <img
          v-viewer
          style="width: 80px; heigth: 52px"
          class="fl"
          v-if="
            oldresList &&
            oldresList &&
            oldresList[activeImg] &&
            oldresList[activeImg].image
          "
          :src="oldresList[activeImg].image"
          alt=""
        />
        <el-tag class="fl" style="margin: 0 0 0 5px"
          >共{{ length }}张发票，当前第{{ activeImg + 1 }}张</el-tag
        >
        <!-- {{oldresList}} -->
        <el-button type="primary" @click="abnormal"
          >已发现发票异常，重新修改发票
        </el-button>
        <el-button type="primary" @click="submitForm"
          >提交本张发票校验结果
        </el-button>
      </el-col>
    </el-col>
  </el-row>
</template>
<script>
import asyncRequest from "@/apis/service/purchase/orderRecord";
import InvoiceHead from "@/views/purchase/orderRecord/components/InvoiceHead";
import resToken from "@/mixins/resToken";
export default {
  name: "orderRecord",
  props: ["id", "newTime", "payNo", "companyNo"],
  components: {
    InvoiceHead,
  },
  mixins: [resToken],
  data() {
    return {
      img: "",
      show: 0,
      length: 0,
      oldItem: {},
      newItem: {},
      oldresList: [],
      resForm: null,
      resList: [],
      options: [
        {
          value: "2",
          label: "通过",
        },
      ],
      examForm: {
        item_list: [],
        issue_date: "",
        subtotal_amount: "",
        subtotal_tax: "",
        total: "",
      },
      examsThis: this.exams,
      activeImg: 0,
      exams: {
        item_list: [],
        issue_date: [
          { required: true, message: "请输入开票日期", trigger: "blur" },
        ],
        subtotal_amount: [
          { required: true, message: "请输入合计金额", trigger: "blur" },
        ],
        subtotal_tax: [
          { required: true, message: "请输入合计税额", trigger: "blur" },
        ],
        total: [{ required: true, message: "请输入价税合计", trigger: "blur" }],
      },
    };
  },

  watch: {
    newTime: function (old, val) {
      if (old !== val) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.show = 0;
      // console.log(this.payNo);
      this.loading = true;
      this.examsThis = this.exams;
      await this.getData();
      await this.initData();
      this.loading = false;
    },
    async nextStep(e) {
      this.resForm = e;
      console.log(this.resForm);
      this.show = 2;
      await this.carouselChange(0);
    },

    async resetForm(item, val) {
      // 重置
      await this.$nextTick(() => {
        console.log(item);
        if (this.$refs.examForm) {
          this.$refs.examForm.resetFields();
          this.$refs.examForm.clearValidate();
          this.examForm.item_list = JSON.parse(JSON.stringify(item.goods));
          this.examForm.issue_date = JSON.parse(
            JSON.stringify(item.issue_date)
          );
          this.examForm.subtotal_amount = JSON.parse(
            JSON.stringify(item.subtotal_amount)
          );
          this.examForm.subtotal_tax = JSON.parse(
            JSON.stringify(item.subtotal_tax)
          );
          this.examForm.total = JSON.parse(JSON.stringify(item.total));
        }
      });
    },
    addGoods() {
      let item = {
        name: "",
        specification: "",
        unit: "",
        quantity: "",
        unit_price: "",
        tax_rate: "",
        tax: "",
        amount: "",
      };
      this.examForm.item_list.push(item);
      this.examForm.item_list.forEach((v1, i1) => {
        this.$set(this.examForm.item_list, i1, v1);
      });
    },
    deleteRow(index) {
      this.examForm.item_list.splice(index, 1);
      // this.$set(this.examForm.item_list, index, this.examForm.item_list[index]);
    },

    async getData() {
      // console.log(this.companyNo);
      const res = await asyncRequest.companydetail({
        companyNo: this.companyNo,
        sid: this.id,
      });
      if (res && res.code === 0) {
        const {
          company_address,
          mobile,
          bank_name,
          bankNo,
          company_license,
          company_name,
        } = res.data || {};
        this.oldresList = [];
        this.oldItem.buyer_address = company_address + mobile;
        this.oldItem.buyer_bank = bank_name + bankNo;
        this.oldItem.buyer_id = company_license;
        this.oldItem.buyer_name = company_name;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    async initData() {
      this.resList = [];
      const res = await asyncRequest.invoiceinfo({ sid: this.id });
      if (
        res &&
        res.code === 0 &&
        res.data &&
        res.data.invoice &&
        res.data.invoice.length > 0
      ) {
        // console.log("整合数据！");
        const { old, buyer, seller, invoice } = res.data || {};
        this.oldItem.seller_address = old.seller_address;
        this.oldItem.seller_bank = old.seller_bank;
        this.oldItem.seller_id = old.seller_id;
        this.oldItem.seller_name = old.seller_name;

        this.newItem.buyer_address = buyer.buyer_address;
        this.newItem.buyer_bank = buyer.buyer_bank;
        this.newItem.buyer_id = buyer.buyer_id;
        this.newItem.buyer_name = buyer.buyer_name;

        this.newItem.seller_address = seller.seller_address;
        this.newItem.seller_bank = seller.seller_bank;
        this.newItem.seller_id = seller.seller_id;
        this.newItem.seller_name = seller.seller_name;
        invoice.forEach((v1) => {
          let x = {
            bstatus: v1.bstatus,
            id: v1.id,
            image: v1.image,
            issue_date: v1.issue_date,
            status: v1.status,
            payid: v1.payid,
            subtotal_amount: v1.subtotal_amount,
            subtotal_tax: v1.subtotal_tax,
            total: v1.total,
            goods: v1.item_list,
          };
          let y = {
            bstatus: v1.bstatus,
            id: v1.id,
            image: v1.image,
            issue_date: v1.invoice_info.issue_date,
            status: v1.status,
            payid: v1.payid,
            subtotal_amount: v1.invoice_info.subtotal_amount,
            subtotal_tax: v1.invoice_info.subtotal_tax,
            total: v1.invoice_info.total,
            goods: v1.invoice_info.item_list,
          };
          this.oldresList.push(y);
          this.resList.push(x);
        });

        this.length = this.oldresList.length;
        this.activeImg = 0;
        // console.log("整合完数据！");
        await this.carouselChange(0);
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    sitDeta(obj) {
      for (let key in obj) {
        if (Array.isArray(obj[key])) {
        } else {
          obj[key] += "";
        }
      }
      return obj;
    },
    async carouselChange(val) {
      if (this.resList.length > 0 && val < this.resList.length) {
        let item = JSON.parse(JSON.stringify(this.resList[val]));
        this.img = item.image;
        if (this.show === 0) {
          this.show = 1;
        } else {
          await this.resetForm(item, val);
        }
      }
    },
    async abnormal() {
      this.loading = true;
      let model1 = {
        sid: this.id,
        payNo: this.payNo,
        status: "3",
      };
      let res = await asyncRequest.again(model1);
      if (res && res.code === 0) {
        const title = "异常已提交，成功返回上一步！";
        this.$notify.success({
          title,
          message: "",
        });
        this.showModelThis = false;
        // 刷新
        this.$emit("refreshAll");
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
      this.loading = false;
    },
    reskeyhas(v) {
      let keyhas = true;
      for (let key in v) {
        keyhas = keyhas && v[key] === "";
      }
      return keyhas;
    },
    async submitForm() {
      await this.$refs.examForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const obj = JSON.parse(JSON.stringify(this.examForm));
          let isok = true;
          let list = JSON.parse(
            JSON.stringify(this.oldresList[this.activeImg].goods)
          );
          if (list.length === 0) {
            this.$message.warning("商品明细不能为空！");
            this.loading = false;
            return;
          }
          list.forEach((v1) => {
            if (this.reskeyhas(v1)) {
              isok = false;
            }
          });
          if (!isok) {
            this.$message.warning("商品明细不能出现整行都为空！");
            this.loading = false;
            return;
          }
          const modal = await this.detectionField(obj, this.activeImg);
          let res = await asyncRequest.invoicesave(modal);
          if (res && res.code === 0) {
            if (this.activeImg + 1 == this.length) {
              console.log("aaaaaaa");
              await this.invoicecheck();
              // let model1 = {
              //   sid: this.id,
              //   payNo: this.payNo,
              //   status: "6",
              // };
              // let res = {};
              // res = await asyncRequest.again(model1);
              // if (res && res.code === 0) {

              //   this.showModelThis = false;
              //   // 刷新
              //   this.$emit("refreshAll");
              // } else if (res && res.code >= 100 && res.code <= 104) {
              //   await this.logout();
              // } else {
              //   this.$message.warning(res.message);
              // }
            } else {
              console.log("bbbbbb");
              await this.carouselChange(++this.activeImg);
            }
          }
          this.loading = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    async invoicecheck() {
      let res = await asyncRequest.invoicecheck({ sid: this.id, type: 2 });
      console.log("ccccccccc");
      if (res && res.code === 0) {
        const title = "发票结果校验成功！";
        this.$notify.success({
          title,
          message: "",
        });
        console.log("ddddddd");
        this.showModelThis = false;
        // 刷新
        this.$emit("refreshAll");
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
      this.loading = false;
    },
    async ValidationList(list) {
      let isOK = true;
      list.forEach((v1) => {
        for (let v2 in v1) {
          if (v1[v2] === "") {
            isOK = false;
          }
        }
      });
      return isOK;
    },
    async detectionField(obj, active) {
      let res = JSON.parse(JSON.stringify(this.resForm));
      let modal = {
        item_list: JSON.parse(JSON.stringify(this.oldresList[active].goods)),
        issue_date: JSON.parse(
          JSON.stringify(this.oldresList[active].issue_date)
        ),
        subtotal_amount: JSON.parse(
          JSON.stringify(this.oldresList[active].subtotal_amount)
        ),
        subtotal_tax: JSON.parse(
          JSON.stringify(this.oldresList[active].subtotal_tax)
        ),
        total: JSON.parse(JSON.stringify(this.oldresList[active].total)),
      };

      for (let i in obj) {
        if (i !== "item_list") {
          if (obj[i] !== modal[i]) {
            res.field.push(i);
          }
        } else {
          console.log(i);
          let isok = true;

          for (let x = 0; x < obj.item_list.length; x++) {
            for (let y in obj.item_list[x]) {
              if (modal.item_list[x]) {
                if (obj.item_list[x][y] !== modal.item_list[x][y]) {
                  isok = false;
                }
              }
            }
          }
          if (!isok) {
            res.field.push("item_list");
          }
        }
      }

      let item = JSON.parse(JSON.stringify(obj));
      let modelX = Object.assign(item, res);
      modelX.field = modelX.field.join(",");
      modelX.id = JSON.parse(JSON.stringify(this.oldresList[active].id));
      return modelX;
    },
    async remoteMethod(query) {
      this.selectLoading = true;
      if (query !== "") {
        this.activeOptions = [];
        this.parmValue.contector = query;
        const res = await asyncRequest.supplierlist(this.parmValue);
        if (res && res.code === 0 && res.data && res.data.list) {
          this.activeOptions = res.data.list;
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      } else {
        this.options = [];
      }
      this.selectLoading = false;
    },
  },
};
</script>

   <style lang="scss" scoped>
.orderRecord {
  .setWidth {
    width: 100% !important;
    // display: flex;
    // display: block !important;
    // .el-input__inner {
    //   display: flex;
    //   width: 1000px !important;
    //   display: block !important;
    // }
  }
  .imgrq {
    max-width: 100%;
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;
    flex-direction: row;
    flex-wrap: wrap;
    padding-bottom: 12px;
    li {
      width: 80px;
      height: 52px;
      border: 2px solid transparent;
      &.active {
        border: 2px solid #63cbe7;
      }
      img {
        display: inline-block;
        width: 100%;
        height: 100%;
      }
    }
  }
  .buy-title {
    display: flex;
    text-align: center;
    align-items: flex-end;
    padding-bottom: 20px;
    > div {
      width: 100%;
      display: block;
      font-size: 17px;
      font-family: "Microsoft Yahei", sans-serif;
      color: #606266;
      font-weight: 700;
    }
  }
  .el-carousel__item h3 {
    color: #475669;
    font-size: 14px;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
  }

  .el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
  }

  .el-carousel__item:nth-child(2n + 1) {
    background-color: #d3dce6;
  }
  .scale {
    li {
      height: 40px;
      line-height: 40px;
      &.fuhao {
        width: 40px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        i {
          width: 40px;
          height: 40px;
          text-align: center;
          line-height: 40px;
          color: #97a8be;
          font-size: 20px;
        }

        &.dengyu {
          i {
            // font-size: 26px;
            transform: rotate(90deg);
            -ms-transform: rotate(90deg); /* IE 9 */
            -moz-transform: rotate(90deg); /* Firefox */
            -webkit-transform: rotate(90deg); /* Safari 和 Chrome */
            -o-transform: rotate(90deg);
          }
        }
      }
      .Addend {
        i.fuhao-i {
          width: 40px;
          height: 40px;
          text-align: center;
          line-height: 40px;
          color: #97a8be;
          font-size: 20px;
        }
      }
    }
  }
}
</style>
