<template>
  <el-dialog
    :title="'新建退货单'"
    :center="true"
    align="left"
    top="8vh"
    width="950px"
    @close="showModelThis = false"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-card style="margin: -20px 0 0 0">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rulesThis"
        ref="ruleForm"
        :size="'mini'"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="退货类型" prop="return_type">
              <el-select
                v-model="ruleForm.return_type"
                style="width: 100%"
                :disabled="type_change"
                @change="return_type_change"
                placeholder="退货类型"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <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="24">
            <el-form-item label="退货备注" prop="remark">
              <el-input
                :disabled="isDetail"
                type="textarea"
                :rows="2"
                maxlength="250"
                show-word-limit
                placeholder="请填写备注"
                v-model="ruleForm.remark"
              /> </el-form-item
          ></el-col>
          <el-col :span="24" v-show="ruleForm.return_type === '2'">
            <el-form-item label="收货信息" :size="'mini'" required>
              <el-table
                :data="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="status" width="100px">
                  <template slot-scope="scope">
                    <el-tag
                      :size="'mini'"
                      :type="scope.row.status == '0' ? 'warning' : ''"
                      v-text="
                        (statusOptions.find((item) => item.id == scope.row.status) || {})
                          .label || '--'
                      "
                    ></el-tag> </template
                ></el-table-column> -->

                <el-table-column label="收货总数量" prop="send_num" width="110" />

                <el-table-column label="退货数量" width="150">
                  <template slot-scope="scope">
                    <digital-input
                      v-show="scope.row.edit"
                      :values="scope.row.return_num"
                      :placeholder="'退货数量'"
                      :min="1"
                      :disabled="false"
                      :max="scope.row.send_num"
                      :position="'right'"
                      :precision="0"
                      :newTime="scope.row.newTime"
                      :size="'mini'"
                      :controls="false"
                      :append="''"
                      @reschange="number_change($event, 'return_num', scope.$index)"
                    />
                    <span v-show="!scope.row.edit">
                      {{ scope.row.return_num }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="50">
                  <template slot-scope="scope">
                    <el-tooltip
                      effect="dark"
                      content="编辑"
                      v-if="
                        !scope.row.edit &&
                        (scope.row.status === '0' || scope.row.status === '1')
                      "
                      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 &&
                        (scope.row.status === '0' || scope.row.status === '1')
                      "
                      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-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="8">
                <el-form-item label="可退数量" prop="good_num">
                  <el-input
                    v-model="ruleForm.good_num"
                    :disabled="true"
                    placeholder="可退数量"
                    maxlength="10"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="退货数量" prop="thnum">
                  <digital-input
                    :values="ruleForm.thnum"
                    :placeholder="'退货数量'"
                    :min="0"
                    :disabled="ruleForm.return_type === '2'"
                    :max="ruleForm.returnT"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :controls="false"
                    :append="''"
                    @reschange="number_change($event, 'thnum')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" 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>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </el-dialog>
</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"],
  mixins: [resToken],
  data() {
    return {
      loading: false,
      showModelThis: this.showModel,
      statusOptions: [
        { id: "0", label: "待公司采购" },
        { id: "1", label: "待库管发货" },
        { id: "2", label: "已发货待收货" },
        { id: "3", label: "已收货" },
        { id: "4", label: "已全部退货" },
      ],
      ruleForm: {
        good_num: "",
        thnum: "",
        return_type: "1",
        orderCode: "", //发货申请单编号
        remark: "", //退货备注
        errorCode: "", //退货原因
        returnT: "",
      },
      rulesThis: this.rules,
      options: [
        {
          value: "1",
          label: "无地址",
        },
        {
          value: "2",
          label: "有地址",
        },
      ],
      rules: {
        errorCode: [
          {
            required: true,
            message: "请选择退货原因",
            trigger: "change",
          },
        ],
        good_num: [
          {
            required: true,
            message: "请输入购买数量",
            trigger: "blur",
          },
        ],
        thnum: [
          {
            required: true,
            message: "请输入退货数量",
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: true,
            message: "请输入退货备注",
            trigger: "blur",
          },
        ],
        return_type: [
          {
            required: true,
            message: "请选择退货类型",
            trigger: "change",
          },
        ],
      },
      get_product_go: [],
      noAddrT: 0,
      hasAddrT: 0,
      type_change: true,
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },

  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 number_change(e, key, index) {
      if (index === undefined) {
        this.ruleForm[key] = e + "" || "0";
        this.$refs.ruleForm.validateField(key);
      } else {
        this.get_product_go[index][key] = e + "" || "0";
        // this.get_product_go[index].newTime = new Date().valueOf() + "";

        this.$set(this.get_product_go, index, this.get_product_go[index]);
        this.ruleForm.thnum = 0;
        this.get_product_go.forEach((s) => {
          this.ruleForm.thnum += parseInt(s.return_num + "");
        });
      }
    },
    return_type_change() {
      const { return_type } = this.ruleForm;
      this.ruleForm.returnT = return_type === "1" ? this.noAddrT : this.hasAddrT;
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const {
            good_num,
            orderCode,
            return_type,
            remark, //退货备注
            errorCode, //退货原因
            thnum,
            returnT,
            returnAddr,
          } = this.sitem;
          this.ruleForm = {
            good_num,
            thnum,
            return_type,
            orderCode, //发货申请单编号
            remark, //退货备注
            errorCode, //退货原因
            returnT,
            returnAddr: [],
          };
          returnAddr.map((s) => {
            s.return_num = s.send_num;
            s.edit = false;
            s.newTime = new Date().valueOf() + "";
            return s;
          });

          this.get_product_go = returnAddr;
        }
      });
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) return;
          const index = this.get_product_go.findIndex((v) => v.edit === true);
          if (index !== -1) {
            this.$message.warning("请保存完当前行！");
            return;
          }
          this.loading = true;
          let model = JSON.parse(JSON.stringify(this.ruleForm));
          const { good_num, thnum, return_type } = model;
          if (thnum + "" === "0") {
            this.$message.warning("退货数量不能为0！");
            this.loading = false;
            return;
          }
          if (parseInt(good_num + "") < parseInt(thnum + "")) {
            this.$message.warning("退货数量不能大于可退数量！");
            this.loading = false;
            return;
          }
          if (return_type + "" === "2") {
            // model.returnAddr[0].return_num = thnum;
            this.get_product_go.forEach((s) => {
              const { addrid, return_num } = s;
              const item = {
                id: addrid,
                return_num,
              };
              model.returnAddr.push(item);
            });
          }

          const { code, data, message } = await asyncRequest.add(model);
          this.loading = false;
          if (code === 0) {
            this.$notify.success({
              title: "添加成功",
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refresh", false);
          } else if (code >= 100 && code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(message);
          }
        } else {
          return false;
        }
      });
    },
    //保存某一行
    checkRow(rowIndex) {
      const { wsend_num, return_num } = this.get_product_go[rowIndex];
      if (!isnumber(return_num)) {
        this.$message.warning("退货数量不规范！");
        return;
      }
      if (parseInt(wsend_num) < parseInt(return_num)) {
        this.$message.warning("退货数量不能大于未发货总数量！");
        return;
      }
      this.get_product_go[rowIndex].edit = false;
      this.get_product_go[rowIndex].newTime = new Date().valueOf() + "";
      this.$set(this.get_product_go, rowIndex, this.get_product_go[rowIndex]);
    },
    //编辑某一行
    editRow(rowIndex) {
      let list = JSON.parse(JSON.stringify(this.get_product_go));
      console.log(list);
      let index = list.findIndex((v) => v.edit === true);
      if (index !== -1) {
        this.$message.warning("请完成其他行的编辑！");
        return;
      }
      this.get_product_go[rowIndex].edit = true;
      this.get_product_go[rowIndex].newTime = new Date().valueOf() + "";
      this.$set(this.get_product_go, rowIndex, this.get_product_go[rowIndex]);
    },
  },
};
</script>

<style lang="scss" scoped></style>
