<template>
  <component
    v-model="activeNames"
    :is="mapComponent[mode].container"
    label-width="80px"
    size="mini"
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"
    v-loading="loading"
  >
    <el-row>
      <el-collapse-item v-if="mode === 'update'" title="业务详情" name="0">
        <show-data-table
          style="margin: 0; padding: 0"
          :sitem="detail"
          v-if="detail"
          :columns="mianColumns"
        >
          <template #before>{{detail.before.tax}}%</template>

          <template #after>{{detail.after.tax}}%</template>

          <template #status>
            <el-tag
              size="mini"
            >{{(approvalStatusOptions.find(({value}) => value === detail.status) || {}).label || '--'}}</el-tag>
          </template>
        </show-data-table>
      </el-collapse-item>

      <el-row :span="24">
        <component
          name="1"
          :is="mapComponent[mode].item"
          v-bind="createLabelField('咨询商品')"
          prop="cgdNo"
        >
          <el-select
            style="width:100%"
            placeholder="选择咨询商品"
            filterable
            remote
            @focus="centerDialogVisible = true"
            v-if="!sitem"
          />
          <el-collapse-transition>
            <div style="display:flex" v-if="sitem">
              <div style="`margin-top:10px;margin-right:${mode === 'create' ? '30px' : '0px'}`">
                <show-goods-data-table
                  :newTime="newTime"
                  v-if="newTime !== ''"
                  :type="'3'"
                  :skucode="sitem.skuCode || sitem.code"
                  :spucode="sitem.spuCode || sitem.code"
                  :iscgd="false"
                  @fetch="getZXProduct"
                  border
                />
              </div>

              <el-tooltip content="重新选择咨询商品" placement="top" v-if="mode !== 'update'">
                <i
                  class="el-icon-circle-close"
                  size="mini"
                  type="text"
                  style="font-size:18px;cursor:pointer;margin-left:10px"
                  @click="resetOrder"
                />
              </el-tooltip>
            </div>
          </el-collapse-transition>
        </component>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="税率" prop="supplierNo">
            <search-tax
              :value="ruleForm.supplierNo"
              :size="'mini'"
              :isDetail="type !== 'add'"
              :placeholder="'税率'"
              @searchChange="taxsearchChange"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="OA编号" prop="oaCode">
            <el-input :disabled="mode === 'update'" placeholder="OA编号" v-model="ruleForm.oaCode" />
          </el-form-item>
        </el-col>

        <el-col :span="8" v-if="mode !== 'update'">
          <el-form-item label="申请人" prop="uid">
            <el-select
              v-model="ruleForm.uid"
              :disabled="mode === 'update'"
              multiple
              remote
              filterable
              :multiple-limit="1"
              clearable
              placeholder="申请人"
              style="width: 100%"
            >
              <el-option
                v-for="item in activeOptions"
                :key="`touserid` + item.id"
                :label="item.nickname"
                :value="item.id"
              >
                <span style="float: left">{{ item.nickname }}</span>
                <span
                  style="
                  float: right;
                  color: #8492a6;
                  font-size: 13px;
                  padding: 0 25px 0 0;
                "
                >{{ item.role_name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              :disabled="mode === 'update'"
              type="textarea"
              placeholder="备注"
              v-model="ruleForm.remark"
              maxlength="2000"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-col :span="24" v-if="mode !== 'update'">
        <el-button size="mini" class="fr" type="primary" @click="submit">保存</el-button>
      </el-col>

      <el-row v-else>
        <el-collapse-item title="待审核" name="4" v-if="detail && Number(detail.status) === 1 && powers.includes('043')">
          <div style="width:600px">
            <wait-approval @confirm="onUpdateStatus" />
          </div>
        </el-collapse-item>
      </el-row>
    </el-row>

    <add-edit
      @refresh="refresh"
      :showModel="centerDialogVisible"
      @cancel="centerDialogVisible = false"
    />
  </component>
</template>

<script>
import addEdit from "./addEdit.vue";
import { statusOptions, ShowDataTableColumns, mianColumns } from "./_columns";
import asyncRequest from "@/apis/service/dataCorrection/order";
import { cg_order_type_options } from "@/assets/js/statusList";
import WaitApproval from "./waitApproval.vue";
import resToken from "../../../../mixins/resToken";
import { isnumber } from "../../../../utils/validate";

// const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]*$/;
const VALID_OA_CODE = function(_1, _2, callback) {
  const { oaCode } = this.ruleForm;
  if (!oaCode) {
    callback(new Error("OA编号不能为空!"));
  } else {
    if (!isnumber(oaCode)) {
      callback(new Error("OA编号必须为纯数字!"));
    } else if (oaCode.length !== 12) {
      callback(new Error("OA编号必须为12位!"));
    } else {
      callback();
    }
  }
};

const VALID_SUPPLIER = function(_1, _2, callback) {
  const { supplierNo } = this.ruleForm;
  console.log(supplierNo);
  if (!supplierNo && Number(supplierNo) !== 0) {
    callback(new Error("请输入税率"));
  } else {
    if (Number(supplierNo) === Number(this.sitem.tax)) {
      callback(new Error("修改的税率不能与咨询商品原税率一致!"));
    } else {
      callback();
    }
  }
};

export default {
  mixins: [resToken],
  components: { addEdit, WaitApproval },
  computed: {
    mode() {
      return this.$route.query.mode || "create";
    },
    id() {
      return this.$route.query.id || "";
    },
    powers() {
      const { btnList } = this.$store.getters;
      const tran = btnList.find(i => i.menu_route == "taxCorrectionDetail") || {};
      const { action } = tran ?? {};
      return action ?? [];
    }
  },
  data() {
    const binded_valid_oa_code = VALID_OA_CODE.bind(this);
    const binded_valid_supplier = VALID_SUPPLIER.bind(this);

    return {
      activeNames: ["1", "2", "3", "4"],
      mianColumns,
      detail: {},
      mapComponent: {
        create: {
          container: "ElForm",
          item: "ElFormItem",
          labelProp: "label"
        },
        update: {
          container: "ElCollapse",
          item: "ElCollapseItem",
          labelProp: "title"
        }
      },
      loading: false,
      newTime: "",
      statusOptions,
      ShowDataTableColumns,
      cg_order_type_options,
      centerDialogVisible: false,
      activeOptions: [],
      wsm_supplier: "",
      wsm_supplierNo: "",
      wsm_name: "",
      wsm_code: "",
      supplierNo: "",
      supplier_name: "",
      order_type: "",
      activeNames: ["0", "1", "2", "3", "4", "5", "10"],
      sitem: null,
      select: "1",
      input: "",
      ruleForm: {
        supplierName: "",
        supplierNo: "",
        remark: "",
        oaCode: "",
        cgdNo: "",
        uid: ""
      },
      approvalStatusOptions: [
        { value: "1", label: "待审核" },
        { value: "2", label: "审核通过" },
        { value: "3", label: "审核驳回" }
      ],
      rules: {
        supplierNo: [
          {
            required: true,
            trigger: "change",
            validator: binded_valid_supplier
          }
        ],
        oaCode: [
          {
            required: true,
            trigger: "change",
            validator: binded_valid_oa_code
          }
        ],
        uid: [
          {
            required: true,
            trigger: "blur",
            message: "请选择申请人"
          }
        ],
        cgdNo: [
          {
            required: true,
            trigger: "change",
            message: "请选择采购单"
          }
        ],
        remark: [
          {
            required: true,
            trigger: "change",
            message: "请输入备注"
          }
        ]
      }
    };
  },
  mounted() {
    this.getAllActive();
    if (this.mode === "update") {
      this.initData();
    }
  },
  methods: {
    taxsearchChange(e) {
      const num = e.split("%");
      this.ruleForm.supplierNo = Number(num[0]);
      this.$refs.ruleForm && this.$refs.ruleForm.validateField("supplierNo");
    },
    // number_change(tax) {
    //   this.ruleForm.supplierNo = tax;
    //   this.$refs.ruleForm.validateField("supplierNo");
    // },
    async onUpdateStatus(payload) {
      this.loading = true;
      const res = await asyncRequest.changestatus({
        id: this.id,
        ...payload
      });
      this.loading = false;

      if (res && res.code === 0 && res.data) {
        this.initData();
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      }
    },
    async initData() {
      //请求详情...
      const res = await asyncRequest.changeinfo({
        id: this.id
      });

      if (res && res.code === 0 && res.data) {
        this.detail = res.data;
        const { code } = this.detail;
        this.refresh({
          spuCode: code,
          skuCode: code
        });
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      }
    },

    createLabelField(value) {
      return {
        [this.mapComponent[this.mode].labelProp]: value
      };
    },
    async submit() {
      try {
        await this.$refs.ruleForm.validate();
        const { supplierName, ...rest } = this.ruleForm;

        const apply_name = this.activeOptions.find(
          ({ id }) => id === rest.uid[0]
        ).nickname;

        const payload = {
          type: "3",
          apply_name,
          code: rest.cgdNo,
          oaCode: rest.oaCode,
          remark: rest.remark,
          apply_id: rest.uid[0],
          change: {
            tax: rest.supplierNo
          }
        };

        this.loading = true;
        const res = await asyncRequest.create(payload);
        this.loading = false;

        if (res && res.code === 0 && res.data) {
          this.$router.push("/dataCorrection/taxCorrection");
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        }
      } catch (e) {
        console.log(e);
      }
    },
    resetOrder() {
      this.sitem = null;
      // this.$refs.ruleForm.validateField(["cgdNo"]);
    },
    refresh(product) {
      this.centerDialogVisible = false;

      this.sitem = { ...product };
      this.newTime = this.getNewTime();
      // spuCode && this.getZXProduct();
    },
    async getZXProduct(result) {
      const { data } = result;
      const { spuCode, tax } = data;
      this.sitem = data;
      // this.ruleForm.supplierNo = Number(tax);
      this.ruleForm.cgdNo = spuCode;
      this.refs.ruleForm.validateField(["cgdNo"]);
    },
    getNewTime() {
      this.newTime = new Date().valueOf();
    },
    async getAllActive() {
      const res = await asyncRequest.accountall({
        ...this.dataForm,
        size: 100000,
        level: "2"
      });

      if (res && res.code === 0 && res.data) {
        this.activeOptions = res.data.list;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    }
  }
};
</script>
