<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.customer_code" placement="top">
              <i class="el-icon-warning-outline" style="margin-right:2px;cursor:pointer" />
            </el-tooltip>
            {{detail.before.customerName}}
          </template>

          <template #after>
            <el-tooltip :content="'客户公司编码 : ' + detail.after.customer_code" placement="top">
              <i class="el-icon-warning-outline" style="margin-right:2px;cursor:pointer" />
            </el-tooltip>
            {{detail.after.customerName}}
          </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="status">
                    <el-tag
                      :size="'mini'"
                      v-text="
                      (statusOptions.find((item) => item.value == sitem.status) || {})
                        .label || '--'
                    "
                    ></el-tag>
                  </template>
                  <template slot="order_type">
                    <el-tag
                      :size="'mini'"
                      v-text="
                      (
                        xs_order_type_options.find(
                          (item) => item.id == sitem.order_type
                        ) || {}
                      ).label || '--'
                    "
                    ></el-tag>
                  </template>
                  <template slot="order_source">
                    <el-tag
                      :size="'mini'"
                      v-text="
                      (
                        xs_order_source_options.find(
                          (item) => item.id == sitem.order_source
                        ) || {}
                      ).label || '--'
                    "
                    ></el-tag>
                  </template>

                  <template slot="supplierName">
                    <span>{{ sitem.supplierName }}</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="companyName">
                    <span>{{ sitem.companyName }}</span>
                    <el-popover placement="top" width="300" trigger="hover">
                      <ul>
                        <li>
                          <span>购买方公司编号：</span>
                          <span>{{ sitem.customer_code }}</span>
                        </li>
                      </ul>
                      <i class="el-icon-warning-outline fr" slot="reference"></i>
                    </el-popover>
                  </template>
                  <template slot="is_active">
                    <span>{{ sitem.is_activity + "" === "1" ? "参与活动" : "不参与活动" }}</span>
                    <span v-if="sitem.is_activity + '' === '0'">
                      /{{
                      (
                      goodtype_options.find(
                      (item) => item.value == sitem.good_type
                      ) || {}
                      ).label || "--"
                      }}
                    </span>
                  </template>
                  <template slot="proof_id">
                    <el-popover
                      placement="top"
                      width="300"
                      trigger="hover"
                      v-if="sitem.proof_type === '1'"
                    >
                      <video width="275" controls class="fl">
                        <source :src="sitem.proof_url" type="video/mp4" />
                        <source :src="sitem.proof_url" type="video/avi" />您的浏览器不支持Video标签。
                      </video>
                      <i
                        class="el-icon-video-camera-solid hover"
                        style="font-size: 18px"
                        slot="reference"
                      ></i>
                    </el-popover>

                    <img
                      v-else-if="sitem.proof_type + '' === '2'"
                      style="width: 28px; height: 28px"
                      :src="sitem.proof_url"
                      class="avatar fl hover"
                      v-viewer
                    />

                    <a
                      v-else-if="sitem.proof_type + '' === '3'"
                      :href="sitem.proof_url"
                      download="比价凭证"
                    >点击下载</a>
                    <span v-else>暂无凭证</span>
                  </template>
                  <template slot="send_type">
                    <el-tag :size="'mini'">
                      {{
                      sitem.send_type + "" === "1"
                      ? "有地址下单"
                      : sitem.send_type + "" === "2"
                      ? "无地址下单"
                      : "--"
                      }}
                    </el-tag>
                  </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.good_code"
              :iscgd="false"
              border
            />
          </component>
        </el-collapse-transition>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="客户公司" prop="supplierNo">
            <search-customer
              :value="ruleForm.supplierNo"
              :size="'mini'"
              :names="ruleForm.supplierName"
              :isDetail="true"
              :placeholder="'客户公司'"
              @searchChange="customerChange"
            />
          </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,
  xs_order_source_options,
  xs_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 { isArray } = Array;
  const { supplierNo } = this.ruleForm;
  if (
    (isArray(supplierNo) && !supplierNo[0]) ||
    (!isArray(supplierNo) && !supplierNo)
  ) {
    callback(new Error("请选择客户公司!"));
  } else {
    if (supplierNo[0] === this.sitem.customer_code) {
      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 == "customerCorrectionDetail") || {};
      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: null,
      mapComponent: {
        create: {
          container: "ElForm",
          item: "ElFormItem",
          labelProp: "label"
        },
        update: {
          container: "ElCollapse",
          item: "ElCollapseItem",
          labelProp: "title"
        }
      },
      loading: false,
      newTime: "",
      statusOptions,
      xs_order_source_options,
      xs_order_type_options,
      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: ""
      },
      goodtype_options: [
        {
          value: "1",
          label: "常规商品"
        },
        {
          value: "2",
          label: "赠品"
        },
        {
          value: "3",
          label: "样品"
        }
      ],
      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: {
    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 { id } = this.detail;
        this.refresh(id);
      } 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: "2",
          apply_name,
          code: rest.cgdNo,
          oaCode: rest.oaCode,
          remark: rest.remark,
          apply_id: rest.uid[0],
          change: {
            customer_code: rest.supplierNo[0],
            customerName: Array.isArray(supplierName)
              ? supplierName[0]
              : supplierName
          }
        };

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

        if (res && res.code === 0 && res.data) {
          this.$router.push("/dataCorrection/customerCorrection");
        } 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 customerChange(e) {
      const { code, label } = e;
      console.log(e, "---");
      this.ruleForm.supplierNo = code ? [code] : [];
      this.ruleForm.supplierName = label || "";
    },
    refresh(id) {
      this.centerDialogVisible = false;
      id && this.getSaleOrderData(id);
    },
    async getSaleOrderData(id) {
      this.loading = true;
      const res = await asyncRequest.saleDetail({ id });
      if (res && res.code === 0 && res.data) {
        this.sitem = res.data;
        this.ruleForm.cgdNo = this.sitem.orderCode;

        if (this.mode !== "update") {
          this.$refs.ruleForm && this.$refs.ruleForm.validateField("cgdNo");
        }

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