<template>
  <div class="goodsCostDetail">
    <div class="goodsCostDetail-main" v-if="powers.some((i) => i == '007')">
      <el-tabs v-model="activeTabs">
        <el-tab-pane label="新建商品成本" name="0" v-if="queryType === 'add'">
          <base-form-normal
            v-if="newTime !== ''"
            :type="queryType"
            :id="queryId"
            :newTime="newTime"
            :sitem="sitem"
            @refresh="refresh"
          />
        </el-tab-pane>
        <el-tab-pane label="商品成本详情" name="1" v-if="queryType !== 'add'">
          <el-collapse v-model="activeNames" style="margin: -18px 0 0 0">
            <tempalte
              v-if="
                queryType === 'editCoin' ||
                queryType === 'editBase' ||
                queryType === 'edit'
              "
            >
              <el-collapse-item title="商品成本详情" name="0">
                <base-form
                  v-if="newTime !== '' && createSource === '1'"
                  :type="queryType"
                  :id="queryId"
                  :newTime="newTime"
                  :sitem="sitem"
                  @refresh="refresh"
                />

                <base-form-normal
                  v-if="newTime !== '' && createSource === '0'"
                  :type="queryType"
                  :id="queryId"
                  :newTime="newTime"
                  :sitem="sitem"
                  @refresh="refresh"
                />
              </el-collapse-item>
            </tempalte>

            <template v-else>
              <el-collapse-item title="基础信息" name="1">
                <show-data-table :columns="basicColumns" :sitem="sitem" border>
                  <template slot="good_img">
                    <template v-if="sitem && sitem.good_img">
                      <div style="max-height: 24px; overflow: hidden">
                        <el-image
                          style="height: 24px; width: 24px; margin-right: 5px"
                          v-for="(img, index) in Array.isArray(sitem.good_img)
                            ? sitem.good_img
                            : sitem.good_img.split(',')"
                          :src="img"
                          :preview-src-list="
                            Array.isArray(sitem.good_img)
                              ? sitem.good_img
                              : sitem.good_img.split(',')
                          "
                          :key="index"
                        />
                      </div>
                    </template>
                  </template>

                  <template slot="create_source">
                    <el-tag
                      size="mini"
                      :type="sitem.create_source === '1' ? 'warning' : ''"
                    >
                      {{ sitem.create_source === "1" ? "咨询成交商品" : "手动创建商品" }}
                    </el-tag>
                    <span v-if="Number(sitem.create_source) === 1"
                      >,咨询采购价 {{ sitem.cgd_price }}</span
                    >
                  </template>

                  <template slot="is_combind">
                    {{ String(sitem.is_combind) === "1" ? "组合商品" : "非组合商品" }}
                  </template>

                  <template slot="packing_spec">
                    <el-tag size="mini">{{
                      (options6.find(({ id }) => id === sitem.supply_area) || {}).name ||
                      "--"
                    }}</el-tag>
                  </template>

                  <template slot="is_auth">
                    <el-tag size="mini">{{
                      (options3.find(({ id }) => id === sitem.is_auth) || {}).name || "--"
                    }}</el-tag>
                  </template>

                  <template slot="good_info_img">
                    <div style="max-height: 24px; overflow: hidden">
                      <el-image
                        v-for="(imgSrc, index) in sitem.good_info_img"
                        :key="imgSrc + index"
                        style="height: 24px; width: 24px; margin-right: 5px"
                        :src="imgSrc"
                        :preview-src-list="[imgSrc]"
                      />
                    </div>
                  </template>

                  <template slot="cat_info">
                    {{
                      sitem.cat_info
                        ? sitem.cat_info.map(({ name }) => name).join("_")
                        : "--"
                    }}
                  </template>

                  <template slot="good_name">
                    <img
                      v-if="sitem.good_thumb_img"
                      v-viewer
                      style="width: 23px; height: 23px; margin: 0 5px 0 0"
                      class="fl"
                      :src="sitem.good_thumb_img"
                      alt
                    />
                    <span>{{ sitem.good_name }}</span>
                    <span v-for="(si, i) in sitem.speclist" :key="si.spec_id + i">
                      <span v-if="i !== 0">-</span>
                      <span v-else>_</span>
                      <span>{{ si.spec_name }}[{{ si.spec_value }}]</span>
                    </span>
                    <el-popover placement="top" width="300" trigger="hover">
                      <ul>
                        <li v-if="newTime !== '' && isDisplayPrivateField('1')">
                          <span>商品成本编号：</span>
                          <span>{{ sitem.spuCode }}</span>
                        </li>
                      </ul>
                      <i slot="reference" class="el-icon-warning-outline fr" />
                    </el-popover>
                  </template>

                  <template slot="noble">
                    <span v-if="sitem.noble_metal">
                      {{ sitem.noble_weight ? sitem.noble_weight : "0" }}g-{{
                        sitem.noble_name
                      }}-{{ sitem.gold_price ? sitem.gold_price : "0" }}元/g-{{
                        sitem.is_gold_price + "" === "0" ? "不" : ""
                      }}启用实时金价-{{ sitem.is_diff + "" === "1" ? "有" : "无" }}工差-{{
                        sitem.config
                      }}-{{ sitem.other_config }}
                    </span>
                  </template>

                  <template slot="weight">{{ sitem.weight }}g</template>
                  <template slot="tax">{{ sitem.tax }}%</template>
                  <template slot="is_stock">{{
                    String(sitem.is_stock) === "0" ? "非库存品" : "库存品"
                  }}</template>
                  <template slot="is_exclusive">{{
                    String(sitem.is_exclusive) === "0" ? "非泰康" : "泰康"
                  }}</template>
                  <template slot="noble_weight">{{ sitem.noble_weight }}g</template>
                  <template slot="is_gold_price">
                    {{ String(sitem.is_gold_price) === "1" ? "是" : "否" }}
                  </template>
                  <template slot="is_diff">
                    {{ String(sitem.is_diff) === "1" ? "有公差" : "无工差" }}
                  </template>

                  <template slot="packing_weight">{{ sitem.packing_weight }}g</template>

                  <template slot="delivery_day">{{ sitem.delivery_day }}天</template>
                  <template slot="lead_time">{{ sitem.lead_time }}天</template>
                  <template slot="sample_day">{{ sitem.sample_day }}天</template>
                  <template slot="delivery_place">{{ delivery_place }}</template>
                  <template slot="origin_place">{{ origin_place }}</template>
                </show-data-table>
              </el-collapse-item>

              <el-collapse-item
                title="子商品信息"
                v-if="sitem.combind_list && sitem.combind_list.length > 0"
                name="4"
              >
                <el-table
                  :data="sitem.combind_list"
                  size="mini"
                  border
                  max-height="350px"
                >
                  <el-table-column
                    label="子商品成本编号"
                    prop="childCode"
                    min-width="160px"
                  />
                  <el-table-column
                    label="子商品名称"
                    prop="child_name"
                    min-width="180px"
                    show-overflow-tooltip
                  />
                  <el-table-column label="组合比例" prop="child_num" width="100px" />
                  <el-table-column label="操作" width="60px">
                    <template slot-scope="scope">
                      <el-tooltip effect="dark" content="查看" placement="top">
                        <i
                          class="el-icon-view tb-icon"
                          @click="onChildProdChange(scope.$index, 'view')"
                        ></i>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>

              <el-collapse-item
                title="固定与阶梯成本"
                name="2"
                v-if="isDisplayPrivateField('1')"
              >
                <show-data-table :columns="ladderColumns" :sitem="sitem">
                  <template slot="demo_fee">{{ sitem.demo_fee }}元</template>
                  <template slot="open_fee">{{ sitem.open_fee }}元</template>
                  <template slot="sample_fee">{{ sitem.sample_fee }}元</template>
                  <template slot="market_price">{{ sitem.market_price }}元</template>
                  <template slot="cgd_price">{{ sitem.cgd_price }}元</template>
                  <template slot="data_table">
                    <el-table size="mini" :data="sitem.nakelist">
                      <el-table-column prop="min_num" label="起订量(>=)" />
                      <el-table-column prop="nake_fee" label="成本单价" />
                      <el-table-column prop="cost_fee" label="工艺费" />
                      <el-table-column prop="delivery_fee" label="物流费" />
                      <el-table-column prop="cert_fee" label="证书费" />
                      <el-table-column prop="mark_fee" label="加标费" />
                      <el-table-column prop="package_fee" label="包装费" />
                      <el-table-column prop="other_fee" label="其他费用" />
                      <el-table-column prop="nake_total" label="成本合计" />
                    </el-table>
                  </template>
                </show-data-table>
              </el-collapse-item>

              <el-collapse-item
                name="3"
                title="采购部门审批"
                v-if="
                  ((status + '' === '0' && ppowers.some((i) => i == '0')) ||
                    (status + '' === '2' && ppowers.some((i) => i == '2')) ||
                    (status + '' === '3' && ppowers.some((i) => i == '3'))) &&
                  queryType === 'view'
                "
              >
                <exam-form
                  :statusList="statusList"
                  :newTime="newTime"
                  :disabled="false"
                  :isMust="false"
                  @searchChange="examForm"
                />
              </el-collapse-item>
            </template>
          </el-collapse>
        </el-tab-pane>

        <el-tab-pane label="最近修改记录" name="2" v-if="queryType !== 'add'">
          <type-change-item
            v-if="newTime !== ''"
            :newTime="newTime"
            :type="'3'"
            :code="queryId"
          />
        </el-tab-pane>

        <el-tab-pane label="审批记录" name="3" v-if="queryType !== 'add'">
          <process-time-line
            v-if="newTime !== ''"
            :newTime="newTime"
            :type="'SPCB'"
            :orderCode="queryId"
          />
        </el-tab-pane>

        <el-tab-pane label="流程图" name="4" v-if="queryType !== 'add'">
          <flow-chart process_id="15" type="SPCB" :orderCode="queryId" />
        </el-tab-pane>
        <el-tab-pane
          label="商品预览"
          name="5"
          v-if="
            queryType !== 'add' && (status === '1' || status === '2' || status === '3')
          "
        >
          <div class="good-preview-box">
            <good-preview
              style="margin: 0 auto"
              v-if="newTime !== ''"
              :newTime="newTime"
              :sitem="sitem"
              :origin_place="origin_place"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>

    <product-modal
      :type="modalType"
      :editIndex="editIndex"
      :editItem="editItem"
      :visible.sync="visible"
    />
  </div>
</template>
<script>
import ShowDataTable from "@/views/standingBook/components/detail-data-table.vue";
import asyncRequest from "@/apis/service/goodStore/goodsCost";
import ProductModal from "./components/productModal.vue";
import privateField from "@/mixins/privateField";
import costForm from "./components/costDetail";
import baseForm from "./components/baseForm";
import baseFormNormal from "./components/baseFormNormal";
import goodPreview from "./components/goodPreview";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import { isArray } from "@/utils/validate";
import {
  packingColumns,
  ladderColumns,
  basicColumns,
  imageColumns,
  sendColumns,
  options3,
  options6,
} from "./columns";

export default {
  name: "goodsCostDetail",
  mixins: [resToken, privateField],
  components: {
    baseFormNormal,
    ShowDataTable,
    ProductModal,
    baseForm,
    costForm,
    goodPreview,
  },
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size", "private_field", "originLevel"]),
    createSource() {
      return this.$route.query.createSource;
    },
    powers() {
      const { btnList } = this.$store.getters;
      const tran = btnList.find((item) => item.menu_route == "goodsCostDetail") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    ppowers() {
      const tran =
        this.$store.getters.roleProcess.find((i) => i.process_type === "SPCB") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },

  data() {
    return {
      statusList: [],
      basicColumns,
      packingColumns,
      options3,
      options6,
      sendColumns,
      imageColumns,
      ladderColumns,
      size: "small",
      activeTabs: "1",
      activeNames: ["0", "1", "2", "3", "4", "5", "6"],
      newTime: "",
      loading: false,
      queryType: "",
      queryId: "",
      status: "",
      sitem: null,
      delivery_place: "",
      origin_place: "",
      editItem: null,
      editIndex: -1,
      visible: false,
      modalType: "",
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    onChildProdChange(index = null, type = "view") {
      this.modalType = type;

      this.editItem = index === null ? null : { ...this.sitem.combind_list[index] };

      this.editIndex = index === null ? -1 : index;
      this.visible = true;
    },
    async initForm() {
      const { id, type } = this.$route.query;
      this.queryId = id;
      this.queryType = type;
      this.activeTabs = type === "add" ? "0" : "1";
      this.loading = true;
      if (this.queryType === "add") {
        this.sitem = {};
        this.getNewTime();
      } else {
        await this.initData();
        await this.getArea("delivery_place");
        await this.getArea("origin_place");
      }

      this.loading = false;
    },
    // 点击业务审核的保存按钮
    async examForm(e) {
      if (!this.loading) {
        let type = "";
        if (e.state + "" === "1") {
          type = "1";
        } else {
          type =
            this.status + "" === "0"
              ? "6"
              : this.status + "" === "2"
              ? "4"
              : this.status + "" === "3"
              ? "5"
              : "";
        }
        await this.setstatus(type, "提交采购部门审核", e.remark);
      }
    },
    async getArea(prop = "delivery_place") {
      const chunks = this.sitem[prop].split(",");
      if (chunks.length !== 3) return "";
      let { data: province } = await asyncRequest.province();
      province = province.find(({ province_code }) => province_code === chunks[0]);
      let { data: city } = await asyncRequest.city({ code: chunks[0] });
      city = city.find(({ city_code }) => city_code === chunks[1]);
      let { data: area } = await asyncRequest.area({ code: chunks[1] });
      area = area.find(({ area_code }) => area_code === chunks[2]);
      this[prop] = [province, city, area].map(({ name }) => name).join("_");
    },
    async setstatus(type, detail, remark) {
      await this.$confirm(`确定要${detail}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let _model = {
            spuCode: this.queryId,
            status: type,
            remark: remark,
          };
          let res = await asyncRequest.status(_model);
          if (res && res.code === 0) {
            this.$notify.success({
              title: "提交成功！",
              message: "",
            });
            await this.initForm();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    handleClick(row) {
      console.log(row);
    },
    async refresh(e) {
      await this.routeReGoto("goodsCost", {});
    },
    async initData() {
      this.loading = true;
      const { code, message, data } = await asyncRequest.detail({
        spuCode: this.queryId,
      });

      this.loading = false;
      if (code === 0) {
        this.sitem = JSON.parse(JSON.stringify(data));
        if (!isArray(this.sitem.good_info_img)) {
          this.sitem.good_info_img = this.sitem.good_info_img.split(",");
        }
        const { status } = this.sitem;
        this.status = status;
        this.getNewTime();
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    getNewTime() {
      this.newTime = new Date().valueOf();
    },
  },
};
</script>
<style lang="scss" scoped>
.goodsCostDetail {
  width: 100%;
  box-sizing: border-box;
  .goodsCostDetail-main {
    box-sizing: border-box;
    padding: 10px;
    height: 100%;
    width: 100%;
  }
  .goodsCostDetail-title {
    border-top: 1px solid #ebeef5;
    span {
      height: 50px;
      line-height: 50px;
      font-family: "微软雅黑", sans-serif;
      font-weight: 400;
      font-style: normal;
      font-size: 16fpx;
      text-align: left;
    }
  }
  /deep/ .ddiv {
    border-top: 1px solid #dcdfe6;
  }
  /deep/ .dtitle {
    width: 40px;
    text-align: center;
    height: 100%;
    min-height: 100%;
    ul {
      padding: 12px 0 0 0;
    }
  }
  /deep/ .dmain {
    padding: 20px 0 0 0;
    width: calc(100% - 40px);
    border-left: 1px solid #dcdfe6;
  }
}
.goodsCostDetail-main {
  .good-preview-box {
    text-align: center;
    box-sizing: border-box;
  }
}
</style>
