<template>
  <el-row :gutter="10">
    <el-col :span="24">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rulesThis"
        ref="ruleForm"
        :size="'mini'"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="退货原因" prop="errorCode">
              <abnormal-cause
                :value="ruleForm.errorCode"
                :placeholder="'退货原因'"
                :type="'5'"
                :size="'mini'"
                @searchChange="errorCode_change"
              />
            </el-form-item> </el-col
          ><el-col :span="16">
            <el-form-item label="退货备注" prop="remark">
              <el-input
                :disabled="isDetail"
                type="textarea"
                maxlength="250"
                show-word-limit
                placeholder="请填写备注"
                v-model="ruleForm.remark"
              /> </el-form-item></el-col
        ></el-row>

        <el-form-item label="收货信息" :size="'mini'" required>
          <el-table
            :data="tableForm.get_product_go"
            border
            :size="'mini'"
            row-key="key"
            max-height="300px"
          >
            <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="退货数量" width="150">
              <template slot-scope="scope">
                <el-form-item style="margin: 0" :size="'mini'">
                  <el-input-number
                    size="mini"
                    v-model="scope.row.return_num"
                    :disabled="!scope.row.edit"
                    :min="0"
                    :max="scope.row.wsend_num"
                    :precision="0"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="未发货数量" prop="wsend_num" width="90" />
            <el-table-column label="已发货数量" prop="send_num" width="90" />

            <el-table-column fixed="right" label="操作" width="50">
              <template slot-scope="scope">
                <el-tooltip
                  effect="dark"
                  content="编辑"
                  v-if="!scope.row.edit"
                  placement="top"
                >
                  <i
                    class="el-icon-edit tb-icon"
                    @click="editRow(scope.$index, 1)"
                  ></i>
                </el-tooltip>

                <el-tooltip
                  effect="dark"
                  content="保存"
                  v-if="scope.row.edit"
                  placement="top"
                >
                  <i
                    class="el-icon-circle-check tb-icon"
                    @click="checkRow(scope.$index, 1)"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </el-col>
    <el-col :span="24" style="text-align: right">
      <el-button type="primary" @click="submitForm" :size="'mini'"
        >保 存
      </el-button>
      <el-button @click="showModelThis = false" v-if="!isDetail" :size="'mini'"
        >关 闭</el-button
      >
    </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: "", //退货备注
        errorCode: "", //退货原因
      },
      rulesThis: this.rules,
      rules: {
        errorCode: [
          {
            required: true,
            message: "请选择退货原因",
            trigger: "change",
          },
        ],
        remark: [
          {
            required: true,
            message: "请输入退货备注",
            trigger: "blur",
          },
        ],
      },
      tableForm: {
        get_product_go: [],
      },
    };
  },
  mounted() {
    this.initForm();
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },

  methods: {
    errorCode_change(e) {
      this.ruleForm.errorCode = e && e.code ? e.code : "";
      this.$refs.ruleForm.validateField("errorCode");
    },
    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 { info, addrs, orderCode } = 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;
          });
          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: "", //退货备注
            errorCode: "", //退货原因
          };
          this.tableForm = {
            get_product_go: [].concat(...l_list),
          };
        }
      });
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          let model = JSON.parse(JSON.stringify(this.ruleForm));
          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 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.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 === 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(this.tableForm.get_product_go));
      let index = list.findIndex((v) => {
        v.edit;
      });
      if (index !== -1) {
        this.$message.warning("请完成其他行的编辑！");
        return;
      }
      this.tableForm.get_product_go[rowIndex].edit = true;
    },
  },
};
</script>

<style>
</style>