<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
          v-if="detail"
          style="margin: 0; padding: 0"
          :sitem="detail"
          :columns="mianColumns"
        >
          <template #before>
            <el-tooltip :content="'供应商公司编码 : ' + detail.before.supplierNo" placement="top">
              <i class="el-icon-warning-outline" style="margin-right:2px;cursor:pointer" />
            </el-tooltip>
            {{detail.before.supplier_name}}
          </template>

          <template #after>
            <el-tooltip :content="'供应商公司编码 : ' + detail.after.supplierNo" placement="top">
              <i class="el-icon-warning-outline" style="margin-right:2px;cursor:pointer" />
            </el-tooltip>
            {{detail.after.supplier_name}}
          </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>
                <show-data-table
                  :newTime="newTime"
                  :sitem="sitem"
                  :columns="ShowDataTableColumns"
                  border
                >
                  <template slot="supplier_name">
                    <span>{{ sitem.supplier_name }}</span>
                    <el-popover placement="top" width="300" trigger="hover">
                      <ul>
                        <li>
                          <span>销售方公司编号：</span>
                          <span>{{ sitem.supplierNo }}</span>
                        </li>
                      </ul>
                      <i class="el-icon-warning-outline fr" slot="reference"></i>
                    </el-popover>
                  </template>
                  <template slot="company">
                    <span>{{ sitem.company }}</span>
                    <el-popover placement="top" width="300" trigger="hover">
                      <ul>
                        <li>
                          <span>购买方公司编号：</span>
                          <span>{{ sitem.companyNo }}</span>
                        </li>
                      </ul>
                      <i class="el-icon-warning-outline fr" slot="reference"></i>
                    </el-popover>
                  </template>

                  <template slot="status">
                    <el-tag
                      :size="'mini'"
                      :type="sitem.status == '0' ? 'warning' : ''"
                      v-text="
                        (statusOptions.find((i) => i.value == sitem.status) || {}).label || '--'
                      "
                    />
                  </template>
                  <template slot="order_type">
                    <el-tag
                      :size="'mini'"
                      v-text="
                      (cg_order_type_options.find((i) => i.id == sitem.order_type) || {})
                       .label || '--'
                      "
                    />
                    <el-popover
                      placement="top"
                      width="300"
                      v-if="sitem.order_type + '' === '1'"
                      trigger="hover"
                    >
                      <ul>
                        <li>
                          <span>备库单编号：</span>
                          <span>{{ sitem.bkcode }}</span>
                        </li>
                      </ul>
                      <i class="el-icon-warning-outline fr" slot="reference"></i>
                    </el-popover>
                  </template>

                  <template slot="wsm">
                    <span>{{ sitem.wsm_name }}</span>
                    <el-popover placement="top" width="300" trigger="hover">
                      <ul>
                        <li>
                          <span>仓库名称编号：</span>
                          <span>{{ sitem.wsm_code }}</span>
                        </li>
                      </ul>
                      <i class="el-icon-warning-outline fr" slot="reference"></i>
                    </el-popover>
                  </template>
                </show-data-table>
              </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-collapse-transition>
          <component
            name="2"
            v-if="sitem"
            :is="mapComponent[mode].item"
            v-bind="createLabelField('商品信息')"
            :style="
              `
               margin-top:10px;
               margin-right:${mode === 'create' ? '30px' : '0px'}
               `
            "
          >
            <show-goods-data-table
              :newTime="newTime"
              v-if="newTime !== ''"
              :type="sitem.order_type"
              :skucode="sitem.skuCode"
              :spucode="sitem.spuCode"
              :iscgd="true"
              border
            />
          </component>
        </el-collapse-transition>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="供应商" prop="supplierNo">
            <search-supplier
              :size="'mini'"
              :value="ruleForm.supplierNo"
              :disabled="mode === 'update'"
              :placeholder="'供应商'"
              :names="ruleForm.supplierName"
              :is-detail="true"
              :no-disabled="true"
              @searchChange="supplierChange"
            />
          </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 { 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 { isnumber } from "@/utils/validate";
import resToken from "@/mixins/resToken";
import addEdit from "./addEdit.vue";

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 { isArray } = Array;
  const { supplierNo } = this.ruleForm;
  if (
    (isArray(supplierNo) && !supplierNo[0]) ||
    (!isArray(supplierNo) && !supplierNo)
  ) {
    callback(new Error("请选择供应商!"));
  } else {
    if (supplierNo[0] === this.sitem.supplierNo) {
      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 == "vendorCorrectionDetail") || {};
      const { action } = tran ?? {};
      return action ?? [];
    }
  },
  data() {
    const bindedValidOACode = VALID_OA_CODE.bind(this);
    const bindedValidSupplier = VALID_SUPPLIER.bind(this);

    return {
      detail: {},
      mianColumns,
      activeNames: ["1", "2", "3", "4"],
      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: bindedValidSupplier
          }
        ],
        oaCode: [
          {
            required: true,
            trigger: "change",
            validator: bindedValidOACode
          }
        ],
        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: {
    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.code === 1005){
          this.$alert('该采购单在结算系统已有有效业务,请解除后再申请',{
            type:'warning',
            message:res.message,
          })
      } 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(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;
        console.log(111)
        const apply_name = this.activeOptions.find(
          ({ id }) => id === rest.uid[0]
        ).nickname;

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

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

        if (res && res.code === 0 && res.data) {
          this.$router.push("/dataCorrection/vendorCorrection");
        }else if(res.code === 1005){
          this.$alert('该采购单在结算系统已有有效业务,请解除后再申请',{
            type:'warning',
            message:res.message,
          })
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      } catch (e) {
        console.log(e);
      }
    },
    resetOrder() {
      this.sitem = null;
      this.ruleForm.cgdNo = "";
      this.ruleForm.supplierName = "";
      this.ruleForm.supplierNo = [];
      this.$refs.ruleForm.validateField(["cgdNo"]);
    },
    async supplierChange(e) {
      const { code, label } = e;
      this.ruleForm.supplierNo = code ? [code] : [];
      this.ruleForm.supplierName = label;
    },
    refresh(cgdNo) {
      this.centerDialogVisible = false;
      this.ruleForm.cgdNo = cgdNo;

      if (this.mode === "create") {
        this.$refs.ruleForm && this.$refs.ruleForm.validateField(["cgdNo"]);
      }

      cgdNo && this.getPurchaseData();
    },
    async getPurchaseData() {
      const { cgdNo } = this.ruleForm;
      if (cgdNo) {
        this.loading = true;

        const { code, data, message } = await asyncRequest.detail({
          cgdNo: cgdNo
        });

        if (code === 0) {
          this.sitem = data;
          const { can } = this.sitem;
          if (can && can.length > 0) {
            this.sitem.class_cat = "";
            can.forEach((x, i) => {
              this.sitem.class_cat += i === 0 ? x.name : "/" + x.name;
            });
          }
          const {
            wsm_supplier,
            wsm_supplierNo,
            wsm_name,
            wsm_code,
            supplierNo,
            supplier_name,
            order_type
          } = this.sitem;
          this.order_type = order_type || "";
          this.supplierNo = supplierNo || "";
          // this.ruleForm.supplierName = supplier_name || "";
          // this.ruleForm.supplierNo = supplierNo ? [supplierNo] : [];
          if (this.order_type === "1") {
            this.wsm_supplier = wsm_supplier || "";
            this.wsm_supplierNo = wsm_supplierNo || "";
            this.ruleForm.wsm_supplierNo = wsm_supplierNo
              ? [wsm_supplierNo]
              : [];
            this.wsm_name = wsm_name || "";
            this.wsm_code = wsm_code || "";
          }

          this.$nextTick(() => {
            this.$refs.ruleForm.validateField(["supplierNo"]);
          });

          this.getNewTime();
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(message);
        }
        this.loading = false;
      }
    },
    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>
