<template>
  <el-row :gutter="10">
    <el-col :span="24">
      <el-form
        :model="ruleForm"
        status-icon
        ref="ruleForm"
        label-width="95px"
        class="demo-ruleForm"
      >
        <el-form-item label="退换货原因" prop="error_msg"  required>
          <el-input
            disabled
            placeholder="退换货原因"
            v-model="ruleForm.error_msg"
          />
        </el-form-item>

        <el-form-item label="退货备注" prop="remark" required>
          <el-input
            disabled
            type="textarea"
            maxlength="250"
            show-word-limit
            placeholder="请填写备注"
            v-model="ruleForm.remark"
          />
        </el-form-item>
        <el-form-item label="仓库信息" :size="'mini'" required>
          <el-table
            :data="tableForm.product_go"
            border
            :size="'mini'"
            row-key="key"
            v-if="!isDetail"
          >
            <el-table-column
              label="仓库名称"
              min-width="300"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ scope.row.wsm_supplier }}{{ scope.row.wsm_name }}
              </template>
            </el-table-column>
            <el-table-column label="下单总数量" width="100" prop="num" />
            <el-table-column label="已发货数量" width="100" prop="send_num" />
            <el-table-column label="未发货数量" width="100" prop="wsend_num" />
            <el-table-column label="退货数量" width="120" prop="return_num" />
          </el-table>
        </el-form-item>
        <el-form-item label="收货信息" :size="'mini'" required>
          <el-table
            :data="tableForm.get_product_go"
            border
            :size="'mini'"
            row-key="key"
          >
            <el-table-column
              label="收货人-联系电话-地址"
              min-width="300"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ scope.row.contactor }}-{{ scope.row.mobile }}-{{
                  scope.row.addr_info
                }}{{ scope.row.addr }}
              </template></el-table-column
            >
            <el-table-column
              label="收货总数量"
              prop="receipt_quantity"
              width="100"
            />
            <el-table-column label="已发货数量" prop="send_num" width="100" />
            <el-table-column label="未发货数量" prop="wsend_num" width="100" />
            <el-table-column label="退货数量" prop="return_num" width="120" />
          </el-table>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

   <script>
import asyncRequest from "@/apis/service/sellOut/sellReturn";
import resToken from "@/mixins/resToken";
import { isnumber } from "@/utils/validate";
export default {
  name: "sellReturn",
  props: ["showModel", "id", "isDetail", "sitem", "showModelThis", "newTime"],
  mixins: [resToken],
  data() {
    return {
      loading: false,
      showModelThis: this.showModel,
      ruleForm: {
        orderCode: "", //出库单编号
        remark: "", //退货备注
        error_msg: "", //退货原因
      },
 
      tableForm: {
        product_go: [],
        get_product_go: [],
      },
    };
  },
  mounted() {
    this.initForm();
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },

  methods: {
    async initForm() {
      this.loading = true;
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const { wsminfo, addrinfo, orderCode,error_msg,remark } = this.sitem;
          console.log(this.sitem);

          // let list =info&&info.length>0?JSON.parse(JSON.stringify(info)):[]; //
          // list.map((v) => {
          //   v.edit = false;
          //   v.return_num = v.return_num || "0";
          //   return v;
          // });
          // this.tableForm.product_go = [].concat(...list);
          // let l_list =addrs&&addrs.length>0? JSON.parse(JSON.stringify(addrs)):[];
          // l_list.map((ele) => {
          //   ele.edit = false;
          //   ele.return_num = ele.return_num || "0";
          //   return ele;
          // });
          this.ruleForm = {
            orderCode: orderCode || "",
            remark:remark|| "", //退货备注
            error_msg: error_msg||"", //退货原因
          };
          this.tableForm = {
            product_go: [].concat(...wsminfo),
            get_product_go: [].concat(...addrinfo),
          };
        }
      });
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          let model = JSON.parse(JSON.stringify(this.ruleForm));
          let arr = JSON.parse(JSON.stringify(this.tableForm.product_go));
          let arr1 = JSON.parse(JSON.stringify(this.tableForm.get_product_go));
          let wsm_code_edit = false,
            addr_edit = false,
            wsm_code_total = 0,
            addr_total = 0;
          let list = [];
          arr.forEach((e) => {
            if (e.edit) {
              wsm_code_edit = true;
            }
            let obj = {
              wsm_code: e.wsm_code,
              return_num: e.return_num,
            };
            wsm_code_total += e.return_num;
            list.push(obj);
          });
          let addr = [];
          arr1.forEach((e) => {
            if (e.edit) {
              addr_edit = true;
            }
            let obj = {
              addrid: e.id,
              return_num: e.return_num,
            };
            addr_total += e.return_num;
            addr.push(obj);
          });
          model.list = list;
          model.addr = addr;
          if (wsm_code_edit) {
            this.$message.warning("仓库信息正在编辑，请保存后再试！");
            this.loading = false;
            return;
          }
          if (addr_edit) {
            this.$message.warning("地址信息正在编辑，请保存后再试！");
            this.loading = false;
            return;
          }
          if (wsm_code_total !== addr_total) {
            this.$message.warning("仓库退货总数不等于收货地址总数！");
            this.loading = false;
            return;
          }
          let res = await asyncRequest.add(model);
          this.loading = false;
          if (res && res.code === 0) {
            const title = this.id === "add" ? "添加成功" : "修改成功";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refresh", false);
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //保存某一行
    checkRow(rowIndex, type) {
      if (type === 0) {
        const { wsend_num, return_num } = this.tableForm.product_go[rowIndex];
        if (!isnumber(return_num)) {
          this.$message.warning("退货数量不规范！");
          return;
        }
        if (parseInt(wsend_num) < parseInt(return_num)) {
          this.$message.warning("退货数量不能大于未发货总数量！");
          return;
        }
        this.tableForm.product_go[rowIndex].edit = false;
      }

      if (type === 1) {
        const { wsend_num, return_num } =
          this.tableForm.get_product_go[rowIndex];
        if (!isnumber(return_num)) {
          this.$message.warning("退货数量不规范！");
          return;
        }
        if (parseInt(wsend_num) < parseInt(return_num)) {
          this.$message.warning("退货数量不能大于未发货总数量！");
          return;
        }
        this.tableForm.get_product_go[rowIndex].edit = false;
      }
    },
    //编辑某一行
    editRow(rowIndex, type) {
      let list = JSON.parse(
        JSON.stringify(
          type === 0 ? this.tableForm.product_go : this.tableForm.get_product_go
        )
      );
      let index = list.findIndex((v) => {
        v.edit;
      });
      if (index !== -1) {
        this.$message.warning("请完成其他行的编辑！");
        return;
      }

      if (type === 0) {
        this.tableForm.product_go[rowIndex].edit = true;
      } else {
        this.tableForm.get_product_go[rowIndex].edit = true;
      }
    },
  },
};
</script>

<style>
</style>