<template>
  <zj-page-container>
    <zj-page-fill>
      <div style="box-sizing: border-box; padding: 20px 20px 0 20px">
        <zj-form-container
          ref="formRef"
          :form-data="formData"
          :form-attributes="{ size: 'mini' }"
        >
          <zj-form-module
            title="价格调整申请审核"
            label-width="120px"
            :form-data="formData"
            :form-items="formItems"
          >
          </zj-form-module>
          <zj-form-module
            v-if="['details', 'examine'].includes($route.query.optionType)"
            title="审批信息"
            label-width="120px"
            :form-data="formData"
            :form-items="shenheItems"
          >
          </zj-form-module>
        </zj-form-container>
      </div>
    </zj-page-fill>
    <div style="text-align: right; box-sizing: border-box; padding: 16px 20px">
      <el-button
        v-if="['edit', 'add'].includes($route.query.optionType)"
        size="mini"
        type="primary"
        @click="save"
        >提交</el-button
      >
      <el-button
        v-if="['examine'].includes($route.query.optionType)"
        size="mini"
        type="primary"
        @click="examine"
        >提交</el-button
      >
      <el-button size="mini" @click="handleClose">取消</el-button>
    </div>
  </zj-page-container>
</template>

<script>
import { required } from "@/components/template/rules_verify.js";
import { getGoodsList, getClassifyList, getGoodsDetail } from "@/api/goods";
import { adminWebsitList } from "@/api/merchantManagement.js";
import {
  goodsApplyAdd,
  goodsApplyUpdate,
  goodsApplyDetail,
  goodsApplyApprove,
} from "@/api/priceAdjustment.js";
export default {
  components: {},
  props: [],
  data() {
    return {
      formData: {
        approveName: "",
        approveRemark: "",
        approveTime: "",
        goodsId: "",
        goods: {},
        goodsApplyItems: [],
        categoryPid: "",
        remark: "",
        status: "",
        websitId: "",
        websitName: "",
        goodsPrice: "",
        orgGoodsPrice: "",
        y_goodsPrice: "",
        y_orgGoodsPrice: "",
      },
      xiangqing: false,
      classifyList: [],
      wangduainshu: [],
      getGoodsListArr: [],
      zhidingGoodsId: "",
    };
  },
  computed: {
    formItems() {
      return [
        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: true,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "申请单号",
            prop: "goodsApplyId",
          },
        },
        {
          isShow: true,
          name: "el-select",
          md: 6,
          options: this.wangduainshu,
          attributes: {
            disabled: this.xiangqing,
            placeholder: "请选择",
            clearable: true,
            filterable: true,
          },
          formItemAttributes: {
            label: "申请商家",
            prop: "websitId",
            rules: [...required],
          },
          events: {
            change: (val) => {},
          },
        },
        {
          isShow: true,
          name: "el-cascader",
          md: 6,
          options: [],
          attributes: {
            options: this.classifyList,
            props: { label: "name", value: "categoryId" },
            disabled: this.xiangqing || this.zhidingGoodsId,
            placeholder: "请选择",
            clearable: true,
            filterable: true,
          },
          formItemAttributes: {
            label: "商品分类",
            prop: "categoryPid",
            rules: [...required],
          },
          events: {
            change: (val) => {
              this.getGoodsListData(val?.[1]);
              this.formData.goodsId = "";
              this.formData.y_goodsPrice = "";
              this.formData.y_orgGoodsPrice = "";
              this.formData.goodsPrice = "";
              this.formData.orgGoodsPrice = "";
              this.formData.goodsApplyItems = [];
            },
          },
        },
        {
          isShow: true,
          name: "el-select",
          md: 24,
          options: this.getGoodsListArr,
          attributes: {
            disabled: this.xiangqing || this.zhidingGoodsId,
            placeholder: "请选择",
            clearable: true,
            filterable: true,
          },
          formItemAttributes: {
            label: "商品名称",
            prop: "goodsId",
            rules: [...required],
          },
          events: {
            change: (val) => {
              var data = this.getGoodsListArr.find(
                (item) => item.value === val
              );
              if (val && data) {
                this.formData.y_goodsPrice = data.data.goodsPrice;
                this.formData.y_orgGoodsPrice = data.data.orgGoodsPrice;
                this.formData.goodsApplyItems = data.goodsSpecs.map((item) => {
                  return {
                    goodsSpecId: item.goodsSpecId,
                    name: item.name,
                    specValue: item.specValue,
                    barCode: item.barCode,
                    costPrice: item.costPrice,
                    price: item.price,
                    applyPrice: "",
                    applyShareAmount: "",
                    applyInnerShareAmount: "",
                    minPrice: item.minPrice,
                    maxPrice: item.maxPrice,
                    shareAmount: item.shareAmount,
                    innerShareAmount: item.innerShareAmount,
                    stockNum: item.stockNum,
                    goodsCode: item.goodsCode,
                  };
                });
              } else {
                this.formData.y_goodsPrice = "";
                this.formData.y_orgGoodsPrice = "";
                this.formData.goodsApplyItems = [];
              }
              this.formData.goodsPrice = "";
              this.formData.orgGoodsPrice = "";
            },
          },
        },

        {
          isShow: true,
          name: "slot-component",
          md: 24,
          attributes: {},
          formItemAttributes: {
            label: "商品规格",
            prop: "goodsApplyItems",
            rules: [...required],
          },
          render: (h, { props, onInput }) => {
            var { formData } = props;
            return (
              <zj-table
                columns={[
                  {
                    columnAttributes: {
                      label: "规格名称",
                      prop: "name",
                    },
                  },

                  {
                    columnAttributes: {
                      label: "规格值",
                      prop: "specValue",
                    },
                  },
                  {
                    columnAttributes: {
                      label: "云闪付69码",
                      prop: "barCode",
                    },
                  },
                  {
                    columnAttributes: {
                      label: "成本价",
                      prop: "costPrice",
                    },
                  },
                  {
                    columnAttributes: {
                      label: "原销售价",
                      prop: "price",
                    },
                  },
                  //{/* -------------------------- */}
                  {
                    columnAttributes: {
                      label: "申请销售价",
                      prop: "applyPrice",
                      width: "240px",
                    },
                    render: (h, { row, column, index }) => {
                      return (
                        <div class="redbordererr">
                          <el-form-item
                            label=""
                            label-width="0px"
                            prop={`goodsApplyItems.${index}.${column.columnAttributes.prop}`}
                            rules={[...required]}
                          >
                            <el-input
                              type="number"
                              value={row[column.columnAttributes.prop]}
                              onInput={(val) => {
                                row[column.columnAttributes.prop] = val;
                              }}
                              onChange={(val) => {}}
                              placeholder="请输入"
                            ></el-input>
                          </el-form-item>
                        </div>
                      );
                    },
                  },

                  {
                    columnAttributes: {
                      label: "申请佣金",
                      prop: "applyShareAmount",
                      width: "240px",
                    },
                    render: (h, { row, column, index }) => {
                      return (
                        <div class="redbordererr">
                          <el-form-item
                            label=""
                            label-width="0px"
                            prop={`goodsApplyItems.${index}.${column.columnAttributes.prop}`}
                            rules={[
                              ...required,
                              {
                                validator: (rule, value, callback) => {
                                  if (value / row.applyPrice > 0.4) {
                                    callback(
                                      new Error(
                                        "申请佣金不能超过申请销售价的40%"
                                      )
                                    );
                                  } else {
                                    callback();
                                  }
                                },
                                trigger: "blur",
                              },
                            ]}
                          >
                            <el-input
                              type="number"
                              value={row[column.columnAttributes.prop]}
                              onInput={(val) => {
                                row[column.columnAttributes.prop] = val;
                              }}
                              onChange={(val) => {}}
                              placeholder="请输入"
                            ></el-input>
                          </el-form-item>
                        </div>
                      );
                    },
                  },
                  {
                    columnAttributes: {
                      label: "申请内部佣金",
                      prop: "applyInnerShareAmount",
                      width: "240px",
                    },
                    render: (h, { row, column, index }) => {
                      return (
                        <div class="redbordererr">
                          <el-form-item
                            label=""
                            label-width="0px"
                            prop={`goodsApplyItems.${index}.${column.columnAttributes.prop}`}
                            rules={[
                              ...required,
                              {
                                validator: (rule, value, callback) => {
                                  if (value / row.applyPrice > 0.4) {
                                    callback(
                                      new Error(
                                        "申请内部佣金不能超过申请销售价的40%"
                                      )
                                    );
                                  } else {
                                    callback();
                                  }
                                },
                                trigger: "blur",
                              },
                            ]}
                          >
                            <el-input
                              type="number"
                              value={row[column.columnAttributes.prop]}
                              onInput={(val) => {
                                row[column.columnAttributes.prop] = val;
                              }}
                              onChange={(val) => {}}
                              placeholder="请输入"
                            ></el-input>
                          </el-form-item>
                        </div>
                      );
                    },
                  },
                  //{/* -------------------------- */}
                  {
                    columnAttributes: {
                      label: "销售价申请下限",
                      prop: "minPrice",
                      width: "240px",
                    },
                  },
                  {
                    columnAttributes: {
                      label: "销售价申请上限",
                      prop: "maxPrice",
                      width: "240px",
                    },
                  },
                  {
                    columnAttributes: {
                      label: "佣金",
                      prop: "shareAmount",
                    },
                  },
                  {
                    columnAttributes: {
                      label: "内部佣金",
                      prop: "innerShareAmount",
                    },
                  },
                  {
                    columnAttributes: {
                      label: "上架库存",
                      prop: "stockNum",
                    },
                  },
                  {
                    columnAttributes: {
                      label: "物料编码",
                      prop: "goodsCode",
                    },
                  },
                ]}
                table-data={this.formData.goodsApplyItems}
              />
            );
          },
        },
        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: true,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "原商品价格",
            prop: "y_goodsPrice",
          },
        },
        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: true,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "原划线价格",
            prop: "y_orgGoodsPrice",
          },
        },
        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: this.xiangqing,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "商品价格",
            prop: "goodsPrice",
            rules: [...required],
          },
        },
        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: this.xiangqing,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "划线价格",
            prop: "orgGoodsPrice",
            rules: [...required],
          },
        },
        {
          isShow: true,
          name: "el-input",
          md: 24,
          attributes: {
            disabled: false,
            type: "textarea",
            rows: 3,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "申请备注",
            prop: "remark",
          },
        },
      ];
    },
    shenheItems() {
      return [
        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: true,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "提交人",
            prop: "createBy",
          },
        },
        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: true,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "提交时间",
            prop: "createTime",
          },
        },
        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: true,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "审核人",
            prop: "approveName",
          },
        },
        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: true,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "审核时间",
            prop: "approveTime",
          },
        },
        {
          md: 6,
          isShow: true,
          name: "el-radio",
          options: [
            { label: "通过", value: "OK" },
            { label: "驳回", value: "FAIL" },
          ],
          attributes: {
            disabled: ["details"].includes(this.$route?.query?.optionType),
          },
          formItemAttributes: {
            label: "审批",
            prop: "status",
            rules: [...required],
          },
        },
        {
          isShow: true,
          name: "el-input",
          md: 24,
          attributes: {
            disabled: ["details"].includes(this.$route?.query?.optionType),
            placeholder: "请输入",
            type: "textarea",
            rows: "2",
          },
          formItemAttributes: {
            label: "审核备注",
            prop: "approveRemark",
          },
        },
      ];
    },
  },
  created() {
    this.zhidingGoodsId = !!this.$route?.query?.goodsId;
    this.xiangqing = ["details", "examine"].includes(
      this.$route?.query?.optionType
    );
    getClassifyList({
      name: "",
      status: true,
    }).then((res) => {
      this.classifyList = res.data;
      if (
        ["add"].includes(this.$route?.query?.optionType) &&
        this.$route?.query?.goodsId
      ) {
        getGoodsDetail({ goodsId: this.$route?.query?.goodsId }).then(
          (res2) => {
            this.formData.goods = { ...res2.data };
            this.formData.goodsId = this.$route?.query?.goodsId;
            this.formData.y_goodsPrice = this.formData.goods.goodsPrice;
            this.formData.y_orgGoodsPrice = this.formData.goods.orgGoodsPrice;
            this.formData.goodsApplyItems = this.formData.goods.goodsSpecs.map(
              (item) => {
                return {
                  goodsSpecId: item.goodsSpecId,
                  name: item.name,
                  specValue: item.specValue,
                  barCode: item.barCode,
                  costPrice: item.costPrice,
                  price: item.price,
                  applyPrice: "",
                  applyShareAmount: "",
                  applyInnerShareAmount: "",
                  minPrice: item.minPrice,
                  maxPrice: item.maxPrice,
                  shareAmount: item.shareAmount,
                  innerShareAmount: item.innerShareAmount,
                  stockNum: item.stockNum,
                  goodsCode: item.goodsCode,
                };
              }
            );
            for (var item of this.classifyList) {
              for (var val of item.children) {
                if (val.categoryId === res2.data.categoryId) {
                  this.formData.categoryPid = [val.parentId, val.categoryId];
                  this.getGoodsListData(res2.data.categoryId);
                }
              }
            }
          }
        );
      }
      if (
        ["edit", "details", "examine"].includes(
          this.$route?.query?.optionType
        ) &&
        this.$route?.query?.goodsApplyId
      ) {
        goodsApplyDetail({
          goodsApplyId: this.$route?.query?.goodsApplyId,
        }).then((res3) => {
          this.formData = {
            ...res3.data,
          };
          this.formData.y_goodsPrice = res3.data.goods.goodsPrice;
          this.formData.y_orgGoodsPrice = res3.data.goods.orgGoodsPrice;
          this.formData.goodsApplyItems = res3.data.goodsApplyItems.map(
            (item) => {
              return {
                applyPrice: item.applyPrice,
                applyShareAmount: item.applyShareAmount,
                applyInnerShareAmount: item.applyInnerShareAmount,
                goodsApplyId: item.goodsApplyId,
                goodsApplyItemId: item.goodsApplyItemId,
                goodsSpecId: item.goodsSpecId,
                name: item.goodsSpec.name,
                specValue: item.goodsSpec.specValue,
                barCode: item.goodsSpec.barCode,
                costPrice: item.goodsSpec.costPrice,
                price: item.goodsSpec.price,
                minPrice: item.goodsSpec.minPrice,
                maxPrice: item.goodsSpec.maxPrice,
                shareAmount: item.goodsSpec.shareAmount,
                innerShareAmount: item.goodsSpec.innerShareAmount,
                stockNum: item.goodsSpec.stockNum,
                goodsCode: item.goodsSpec.goodsCode,
              };
            }
          );
          console.log(this.classifyList, res3.data.goods.categoryId);
          for (var item of this.classifyList) {
            for (var val of item.children) {
              if (val.categoryId === res3.data.goods.categoryId) {
                this.formData.categoryPid = [val.parentId, val.categoryId];
                this.getGoodsListData(res3.data.goods.categoryId);
              }
            }
          }
          if (["examine"].includes(this.$route?.query?.optionType)) {
            this.formData.status = "";
          }
        });
      }
    });
    adminWebsitList({
      pageNum: 1,
      pageSize: -1,
      params: [{ param: "status", compare: "=", value: "ON" }],
    }).then((res) => {
      this.wangduainshu = res.data.records.map((item) => ({
        value: item.websitId,
        label: item.name,
      }));
    });
  },
  methods: {
    // 获取商品列表
    getGoodsListData(categoryId) {
      if (categoryId) {
        getGoodsList({
          categoryId: categoryId || "",
          status: true,
          pageNum: 1,
          pageSize: -1,
        }).then((res) => {
          this.getGoodsListArr = res.data.records.map((item) => {
            return {
              data: item,
              goodsSpecs: item.goodsSpecs,
              label: item.goodsName,
              value: item.goodsId,
            };
          });
        });
      }
    },
    handleClose() {
      // this.$refs?.formRef?.resetFields();
      // this.$data.formData = this.$options.data().formData;
      // this.$router.go(-1);
      this.$router.replace({ path: "/goods/priceAdjustment" });
    },
    save() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          (this.formData?.goodsApplyId ? goodsApplyUpdate : goodsApplyAdd)({
            ...this.formData,
          }).then((res) => {
            this.$message({
              type: "success",
              message: "提交成功",
            });
            this.handleClose();
          });
        }
      });
    },
    examine() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          goodsApplyApprove({
            ...this.formData,
          }).then((res) => {
            this.$message({
              type: "success",
              message: "审批成功",
            });
            this.handleClose();
          });
        }
      });
    },
  },
};
</script>

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